I am trying to send json data to my Symfony2 controller, using $.ajax method of jquery (1.12.4).
My javascript:
var category_type = 2;
var json_data = JSON.stringify(category_type);
$.ajax({
type: "POST",
url: Routing.generate('homepage'),
contentType: 'application/json',
dataType: "json",
data: json_data,
beforeSend: function (xhr){
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
},
success: function (result, status, xhr) {
console.log(result);
console.log(status);
},
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
My controller:
/**
* @Route("/", name="homepage", options={"expose"=true})
*/
public function indexAction(Request $request) {
if($request->isXmlHttpRequest()){
$content = $this->get("request")->getContent();
$cat = json_decode($content, true);
var_dump($content);
exit;
}
else {
echo 'Sorry!';
exit;
}
However I get the message Sorry! everytime. Now I am not sure if I used xhr: setRequestHeader("X-Requested-With","XMLHttpRequest"),
correctly. But without it I get the same result.
I've also tried removing the if/else
condition and tried $content = $this->get("request")->getContent();
. But when I do var_dump($content);
, I get an empty string ie. string '' (length=0)
Question:
- Why does
$request->isXmlHttpRequest()
returnfalse
? - How do I set the request header?
- Is this the correct way to send json data to the server(
$.ajax
)? - Is this the correct way to receive data in the controller(
$this->get("request")->getContent();
)?