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.
headerfunction when you useJsonResponse. Comment line :header('Content-Type: application/json');