PumpkinSeed PumpkinSeed - 14 days ago 11
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.
Server-side:

/**
* @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
development.domain.com/index.php/api/v2/advertisement/all
with Content type:
application/x-www-form-urlencoded
I got a proper JSON object. If I try the same with
application/json
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

Client-side:

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

function sendAjaxRequest(method, url, data, contentType) {
var response;
$.ajax({
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
undefined
on the client-side. I try to use the JSON.stringify on the response, because it is a JSON object.

Answer

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;
            callback(JSON.parse(response));
        }
    };
    xhttp.open(method, url, true);
    xhttp.setRequestHeader("Content-Type", contentType);
    xhttp.send(data);

    return response;
}

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

Comments