utkarsh2k2
utkarsh2k2

Reputation: 1096

$request->isXmlHttpRequest() returns false

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:

  1. Why does $request->isXmlHttpRequest() return false?
  2. How do I set the request header?
  3. Is this the correct way to send json data to the server($.ajax)?
  4. Is this the correct way to receive data in the controller($this->get("request")->getContent();)?

Upvotes: 1

Views: 4901

Answers (1)

Goku
Goku

Reputation: 2139

Try it in your ajax call:

data: { json_data }

instead of :

data: json_data

And if you want to see POST data from request you have to do this :

dump($request->request);

=> I advise you to use the dump function (SF 2.6 => see doc to use it)

EDIT

Try to do this simple call and if it works you just have to reproduce this with your own data:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

Upvotes: 1

Related Questions