user4457363
user4457363

Reputation:

Cross-domain Ajax - Why isXmlHttpRequest return false?

I'm doing an Ajax request like this :

    $.ajax({
        type: "POST",
        url: Routing.generate('check_login_ajax'),
        dataType: 'json',
        data: {
            _username: $('#_username').val(),
            _password: $('#_password').val(),
            _remember_me: false,
            _csrf_token: $('#_csrf_token').val()
        }
    }).done(function (data) {
        console.log(data);
    });

The php controller :

    public function CheckLoginAjaxAction() {
            $request = $this->get('request');

            $success = false;
            $responseCode = 300;
            if ($request->isMethod('POST') && $request->isXmlHttpRequest()) {
                    $responseCode = 200;
                    $success = true;
            }

            $return = json_encode(array('responseCode' => $responseCode, 'success' => $success));
    }

I have, on my xbo.dev site :

Object {responseCode: 200, success: true}

And I have, on my subdomain blog.xbo.dev :

Object {responseCode: 300, success: false}

So, my request works but it's not considered as a valid POST xml request. Why ?

By the way, I have another little problem. When I make an Ajax request from the subdomain, it doesn't appear in the Symfony2 debug toolbar. Do you know how to change it and if it is possible ?

Symfony2 debug toolbar

Thanks

Upvotes: 1

Views: 601

Answers (1)

user4545769
user4545769

Reputation:

I'm assuming you're using jQuery for your AJAX call, in which case jQuery tries to be smart when it detects a cross-domain request and will change the format of the request to JSONP. JSONP effectively just creates a script tag to the requested URL and runs the resultant script (more details on Wikipedia). So the request coming into your controller will actually be a GET rather than a POST (because jQuery is requesting a script) and is also why it won't appear in the Symfony toolbar as an AJAX request.

To get around this you should look into Cross Origin Resource Sharing (CORS) which is specifically to solve doing cross domain AJAX requests like this. The details of implementing this are beyond the scope of this answer and will be contingent on your browser support and JavaScript setup.

Upvotes: 1

Related Questions