Bruno García
Bruno García

Reputation: 187

Jquery's Ajax with CORS not working

I'm having a hard time trying to make work a simple jQuery's Ajax between two domains.

When I try to execute Ajax in site A, in the developers tool's Network section I get '404 Not found' in the GET methods related with Site B. I also see this message in the console: "...missing CORS header 'Access-Control-Allow-Origin'"

In "site A" I've this:

<script>
    var xhr = new XMLHttpRequest();
    xhr.open("get", "http://domainB.com/resource.php", true);
    xhr.onload = function () {
        console.log('Connected!');
    };
    xhr.send(null);

    $.ajax({
        url: 'http://domainB.com/resource.php',
    }).done(function ($result) {
        //somecode
    });
</script>

And in the resource's server ("Site B"):

<?php    
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST');
    header("Access-Control-Allow-Headers: X-Requested-With");
    //somecode

This is my first time with CORS and I really have no much idea what's wrong.

Thank you

Upvotes: 0

Views: 1636

Answers (2)

Bruno Garc&#237;a
Bruno Garc&#237;a

Reputation: 187

Finally I got an answer in this post: http://www.html5rocks.com/en/tutorials/cors/. It seems that the problem was in my Ajax code, I just added some properties and now it's working perfectly. This is how my Ajax looks now:

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            contentType: 'text/plain',
            xhrFields: {
                withCredentials: false
            },
        }).done(function ($result) {
            //somecode
        });

Upvotes: 1

ram singh
ram singh

Reputation: 140

add this code at start of php page

http://domainB.com/resource.php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-  Size, 
X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

Upvotes: 0

Related Questions