Sending variables by ajax I receive an empty object

0

I am trying to send a variable that I get from an input to my controller in the following way

$(document).ready(function() {
    $(".autocomplete").on('blur',function(){
        var occ = $("#oculto_id").val();
        $.ajax({
            url: "{{ path('reg_validacion') }}",
            type: "POST",
            data: occ,
            success: function(data) {
                alert(data);
                //si hago un alert(occ); me imprime la variable,lo que significa que el input no esta en null
            }
        });
    });
});

but the alert (data) returns me:

and in the controller I'm not receiving anything.

public function validatection(Request $request)
{
    $varpost=$request->query->get("occ");

    dump($varpost);
    die();
    return $varpost;

}

Any suggestions on how I can get the occ value of the input in the controller?

    
asked by matteo 03.08.2018 в 20:09
source

2 answers

1

Problem, the OCC value is not being sent correctly,

In ajax it would be

data: {occ:occ}
// o de esta maneta
data: {occ}
// o de esta maneta
data: {"occ":occ}

Remember that you are sending by POST and in symfony the variable is obtained in this way

// parametros por $_GET
$request->query->get('occ');

// parametros por $_POST
$request->request->get('occ');

If you can not deal with these, try one of these:

$this->container->get('request_stack')->getCurrentRequest();
$this->get('request');
$request->query->get('keyWord');
$request->request->get('keyWord');
$request->get('keyWord');
$request->request->getInt('keyWord');
$request->query->all();
    
answered by 03.08.2018 / 20:27
source
1

The problem is in the controller, when you send the data by GET method, you receive it in this way:

$varpost=$request->query->get("occ");

And when you send the data by POST, you should receive it in this way.

$varpost=$request->request->get("occ");

You can also send it directly via the URL (GET), adjusting your url in the ajax method in this way:

url =  "{{ path('ruta_del_controlador', {'datos_envio':'x1'}) }}";
url = url.replace('x1', variable);
    
answered by 03.08.2018 в 20:26