Question

Good evening everybody!

I would like to send JSON Post Data to a Symfony Controller without form, but it doesn't work. I build a JSON data line and it is well built, it is NOT the problem. When I send my data with AJAX, the request is not filled.

Here is my Javascript code:

function validerSession()
{
    //I don't describe the composition of the dataline.
    var dataObject = JSON.stringify(obj); //My dataline JSONified

    $.ajax({
        type: "POST",
        url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
        data: dataObject,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (donnees) {
            alert("Hello");
        }
    });
}

The AJAX call work.

Here is the PHP Symfony Controller method which received data:

public function validerSessionAction(Partie $partie, Session $session)
{
    $request = $this->get('request');
    $data = json_decode($request->getContent());

    $serializer = $this->container->get('jms_serializer');
    $response = $serializer->serialize($data, 'json');
    return new Response($response);
}

But there is not any data in $data.

EDIT : An example of the dataline JSONified

{"trappes":{"1":{"id":"134","montant":"5000"},"2":{"id":"135","montant":"15000"},"3":{"id":"136","montant":"20000"},"4":{"id":"137","montant":"0"}}}

Do you have any idea ? I'm sure this is a common issue. Thank you for your participation !

CloudCompany

Was it helpful?

Solution

I found the solution. It's not really difficult.

It is not necessary to JSonify data. The controller has the capability to understand the original datatype.

So here is my simplified AJAX call:

function validerSession()
{
    obj = new Object();
    obj["title"] = "Title for example";

    $.ajax({
        type: "POST",
        url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
        data: obj,
        success: function (donnees) {
            data = Parse.JSON(donnees);
            alert(data.title); //Show "Title for example"
        }
    });
}

And here is my Controller. It can recover data as an array of values.

public function validerSessionAction(Partie $partie, Session $session)
{
    $request = $this->get('request');
    $data = $request->request->all();

    $serializer = $this->container->get('jms_serializer');
    $response = $serializer->serialize($data["title"], 'json');
    return new Response($response);
}

Thanks for the help!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top