Skip to content Skip to sidebar Skip to footer

Ajax Request Failed With Unknown Reason (jquery)

I have a service which returns JSON data: http://api.drag2droid.shamanland.com/captcha?base64 I'm trying to execute simple AJAX request: $.ajax({ type: 'get', url: 'http://

Solution 1:

Thank you all, guys, I found my problem. After I copy-paste code PHP-from this post, I decided to optimize it - I placed all statements into if METHOD == OPTIONS. This is fault.

Header Access-Control-Allow-Origin should be returned not only for OPTIONS request.

My updated code works fine:

if (isset($_SERVER["HTTP_ORIGIN"])) {
    header("Access-Control-Allow-Origin: {$_SERVER["HTTP_ORIGIN"]}");
}

if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") {
    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"])) {
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    }

    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"])) {
        header("Access-Control-Allow-Headers: {$_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]}");
    }

    exit(0);
}

Thanks to @Patrick Evans second comment, but it's already deleted =)

Solution 2:

You are attempting to load a resource from another domain. Because the service you are requesting the JSON from is not configured to allow this, the request is failing.

See: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Solution 3:

When we give the type as "json", the response should be a strict json object. Please verify the response or post it here.

See below the excerpts from the URL: JQuery API

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

Solution 4:

The reason is because of CORS (ie., Cross domain issue). To overcome use jsonp instead of json.

dataType:"jsonp",

Post a Comment for "Ajax Request Failed With Unknown Reason (jquery)"