Ajax request fails, can't see why

25,400

Solution 1

$.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
         if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) 
              return;  // it's not really an error
         else
              // Do normal error handling
});

Solution 2

What is probably the problem

I think I know your problem here. Seemingly you are loading a page one some protocol+domain+port (eg. "http://localhost/"), but then invoke AJAX request to a different protocol, domain or port (in this case probably only port differs: "http://localhost:8000/products").

This way you are probably hitting Same Origin Policy limitation, which is security feature of your browser. In such cases browsers may indicate that specific request has been "cancelled" (because browser blocked it).

Solution

There are multiple solutions to your problem:

  • (easiest) stick to the same protocol+domain+port for both original site and the endpoint requested by AJAX,
  • (second easiest) build an end point on the server, so eg. "http://localhost/products" will call "http://localhost:8000/products" in the background and will return its response (as a walkaround for SOP),
  • some more complex solutions like JSONP, CORS etc. (more here: https://stackoverflow.com/a/8467697/548696),

Solution 3

Try using just

$.ajax({
  url: "http://localhost:8000/products", 
  dataType: 'json',
  success: function(data){
            console.log("You made it!");
        },
        error: function(xhr) {
           console.log("Error: " + xhr.statusText);
       }
});

Instead of using done callback , you can use code line inside success or complete callback. Its quite simple and cleaner.

Share:
25,400
holyredbeard
Author by

holyredbeard

Updated on December 16, 2020

Comments

  • holyredbeard
    holyredbeard over 3 years

    I've created an API that returns data in json, and now I'm creating an app to test the API by receive the data and use it on the page. However, my ajax code (se below) fails by some reason, and the error says just "error" (Error: error).

    What can be wrong with the code?

    the code:

        $.ajaxSetup ({
          url: "http://localhost:8000/products", // <--- returns json
          type: "GET",
          headers:{
            "Accept":"application/json",
            "Content-type":"application/x-www-form-urlencoded"
          }
        })
        $.ajax({
            success: function(data){
                console.log("You made it!");
            },
            error: function(xhr) {
               console.log("Error: " + xhr.statusText);
           }
        }).done(function(data){
            console.log(data);
        })
    

    This is the info I get in Chrome (Inspector -> Network):

    Name: products localhost/, Method: GET, Status: (cancelled), Type: Pending, Initiator: jquery-latest.js:8434 Script, Size: 13B 0B, Time: 95ms 0.0 days