JQuery Ajax POST request in Symfony 4 profiler

It took me a while to figure out how to get data in Symfony 4 via a JQuery Ajax POST request. I will put the code it might help someone but it raises 2 questions I cannot find answer yet. Here is the code:

Javascript:

function sendData() {
    $.ajax({
        url: 'response2',
        method: 'POST',
        processData: false,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "name": "John", "time": "2pm" }),
        dataType: "json",
        success: function (data) {
            console.log(data);
        }
    });
}

PHP (in Symfony Controller)

    /**
     * @Route("/response2", name="test_response2")
     * @param Request $request
     * @return Response
     */
    public function response2 (Request $request) : Response
    {
        $data1 = $request->getContent();
        $data2 = json_decode($data1);

        return $this->json(['data1' => $data1, 'data2' => $data2, 'data3' => $data2->name]);
   
    }

and the result is as expected and all works fine

{data1: "{"name":"John","time":"2pm"}", data2: {name: "John", time: "2pm"}, data3: "John"}

However, I still do not understand something. If I do a very simple Ajax request for example like this:

function sendData() {
    $.ajax({
        url: 'response2',
        method: 'POST',
        data: { "name": "John", "time": "2pm" },
        success: function (data) {
            console.log(data);
        }
    });
}

Even if it is a POST request, I have noticed in the Symfony profiler that the data are not shown in a "POST parameters" section as I was expected but in the "Request Content" section as Raw data.

Also I found that the header contained 2 references to the type Content-Type : Content-Type: text/plain;charset=UTF-8 and Content-Types: application/json; charset=utf-8. I was not able to find any information about Content-TypeS

So my questions are:

  1. why and how ajax data are detected as raw data in Symfony and not as POST data?
  2. what is the means Content-TypeS, in what is it different than Content-Type?

Thanks in advance

Source: Symfony4 Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *