Robin saint georges
Robin saint georges

Reputation: 45

How to properly get a parameter send using ajax in a Symfony controller (annotation)?

I have been struggling for the past 2 days and none of the answer I've find so far on the internet have helped me so far.

I'm trying to pass data using ajax on a symfony project. The goal is to update a twig value .

So i've set an ajax call like this :

$searchbar = $("#searchBar");
var btnSearch = document.getElementById("btnRecherche");

btnSearch.onclick = chargeClientsData;

function chargeClientsData()
{
    let searchVal = $("#searchBar").val();
    console.log(searchVal);

    $.ajax({
        url: "{{ path('showIt') }}", // point to server-side PHP script
        dataType: 'json',
        data: {data :  searchVal },
        type: 'POST',
        success: function(data){
            console.log(data);
            $('#monelement').html("test");
        }
    });


}

And I'm tring to get if using this controler :

/**
 * @route("/showIt}", name="showIt", methods="POST")
 * @param $request
 * @return Response
 */
public function showIt(Request $request){

    var_dump($request);
    if($request->isXmlHttpRequest()){
        $search = $request->query->get('data');
        var_dump($search);
        $response = $this->checkValidRequest($request);
        return $response->setData(['search' => $search ]); // working
    }

    $response = $this->checkValidRequest($request);
    $response->setStatusCode(500);
    return $response;

}

The var_dump($request) show none of the value, and of course var_dump($search) come as NULL.

In twig, $("#searchBar"); send the righ value, and I do get a success but with null values

Is there something that I did wrong ?

Thank for the help !

Upvotes: 0

Views: 2979

Answers (1)

iiirxs
iiirxs

Reputation: 4582

Since you are using a POST request, you can get the your POST parameter in your controller like this:

$search = $request->request->get('data');

instead of

$search = $request->query->get('data');

that you are currently using. Note that $request->query->get('data') is used for GET method.

Upvotes: 1

Related Questions