PumpkinSeed PumpkinSeed - 1 year ago 119
Javascript Question

PHP Symfony API and jQuery Ajax request

I have a problem between server and client side. I have a Rest API on server side with PHP Symfony.

* @Route("/advertisement/all", name="advertisement_get_all")
* @Method("POST")
public function getAllAdvertisement()
header('Content-Type: application/json');
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
$content = $this->get("request")->getContent();
$advertisemenetService = $this->container->get("advertisementservices");
$response = $advertisemenetService->getAllAdvertisement($content);
} else {
$response = new \stdClass();
$response->error = true;
$response->message = "Error occurred: You aren't authorized!";

return new JsonResponse($response);

If I try it in DHC Rest Client Chrome Extension for that
with Content type:
I got a proper JSON object. If I try the same with
the symfony say the following error for me:
Failed to start the session because headers have already been sent by "" at line 0. (500 Internal Server Error)

JSON response example


How I said on the API tester I got a proper JSON object. My clientside code:

function sendAjaxRequest(method, url, data, contentType) {
var response;
method: method,
url: url,
data: data,
dataType: 'json',
contentType: contentType,
success: function(msg) {
response = msg;
return jQuery.parseJSON(response);
response = sendAjaxRequest("POST", "{{ path('advertisement_get_all') }}", '', 'application/x-www-form-urlencoded');
document.getElementById("loader-container").innerHTML = response;

In this case I always get
on the client-side. I try to use the JSON.stringify on the response, because it is a JSON object.

Answer Source

I throw away the jQuery Ajax, because it was too dificult to slow this problem, and got back to the XMLHttpRequest and using a callback function which I called when the AJAX getting the response.

function sendAjaxRequest(method, url, data, contentType, callback)
    var response
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            response = xhttp.responseText;
    xhttp.open(method, url, true);
    xhttp.setRequestHeader("Content-Type", contentType);

    return response;

The main problem, which occured: The response handler function always run sooner than the Ajax response arrived.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download