2

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

holyredbeard
  • 19,619
  • 32
  • 105
  • 171

5 Answers5

10

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),
Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
5
$.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
});
Pavel Hodek
  • 14,319
  • 3
  • 32
  • 37
  • 10
    Care to explain your answer? – Tadeck Dec 15 '12 at 13:27
  • 3
    Error with status or readyState == 0 can occur when you cancel ajax request before it completes, or when you navigate to another page or when you refresh page. Detail information to error you can get from first or third parameter - try log them to console using `console.log(...)` to see what happens. – Pavel Hodek Dec 15 '12 at 13:32
  • @PavelHodek: I tried your code and readyState and status was 0, so no "real" error then I suppose? – holyredbeard Dec 15 '12 at 13:49
  • @holyredbeard I think no error then. Try also inspect response with Firebug (Firefox extension) or with Fiddler or with Developer Tools within Chrome - you can there see what data is comming as Response. If everything works and data is OK, then no error occurs. – Pavel Hodek Dec 15 '12 at 14:13
  • @holyredbeard There is Net tab and within it is XHR tab - it's place where you can view all Ajax Request and Response of current page (url, content, headers,...). You can also debug JavaScripts using Firebug, just place breakpoint in JavaScript source in Firebug (tab Script) - there you can view any object information. – Pavel Hodek Dec 15 '12 at 14:47
2

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.

Sudhanshu Yadav
  • 2,323
  • 18
  • 18
0

Why dont you try and merge the two ajax calls in one. and also try and change type = "POST"

$.ajax({
    type: "POST",
    url: "http://localhost:8000/products",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    error: function(errMsg) {
        alert(errMsg);
    }
});
Moiz
  • 2,409
  • 5
  • 27
  • 50
  • "_two ajax calls in one_"? There is only one call. If you are talking about invoking `$.ajaxSetup()`, then maybe OP wants to use it in the future (like simplifying the code by applying DRY principle). – Tadeck Dec 15 '12 at 13:30
  • @Tadeck: Thanks for the info.i didnt knew :) – Moiz Dec 15 '12 at 13:32
  • BTW `$.ajaxSetup()` doesn't make any ajax call, it's setup of ajax module only. – Pavel Hodek Dec 15 '12 at 14:51
0

I think your browser cached the error, or may be there are problems in setting headers properly, so try adding this way over there in the $.ajaxsetup():

    $.ajaxSetup ({
      url: "http://localhost:8000/products", // <--- returns json
      type: "GET",
      dataType: 'json',
      cache: false,
      contentType: "application/json"
    });

try this way once and see if works.

Jai
  • 74,255
  • 12
  • 74
  • 103
  • Still gets an error, however the URL gets somewhat different in the console when adding that line: GET http://localhost:8000/products?_=1355580034481 (the question mark and all the numbers is added). – holyredbeard Dec 15 '12 at 14:04