1

I am trying to 'GET' data from my WebAPI using JQuery $.ajax(). Here is my code:

$.ajax({
              type: "GET",
              url: "http://localhost:62412/api/RandomData?startTime=2013-02-23%2005%3A00%3A00&callback=?",                                
              dataType: "jsonp",                 
              success: function (data) {
                  alert("success");
              },
              error: function (errorData) {                 
                alert("fail");
              }// When Service call fails
          });

I can see that the WebAPI works properly and returns the data successfully. But on the client side I always get the 'fail' alert. I can see the data in firebug.

Can anybody please let me know why the 'error' function is getting invoked when the response status is '200'?

usp
  • 797
  • 3
  • 10
  • 24
  • Can you maybe post the data that is returned by the server? – david Apr 02 '13 at 19:26
  • [{"ID":"002940","Name":"William","Latitude":31.56,"Longitude":-87.0},{"ID":"002940","Name":"Brian","Latitude":31.56,"Longitude":-86.98}]This is the JSON I get from the server. – usp Apr 02 '13 at 19:31
  • See http://stackoverflow.com/questions/5943630/basic-example-of-using-ajax-with-jsonp – Grilse Apr 02 '13 at 19:37

2 Answers2

1

The $.ajax call can fail if the downloaded data is not a valid json data and it could be correctly parsed.

Change the error callback and check the error message:

error: function (data, msg) {                 
            console.log(msg)
          }
Bechir
  • 987
  • 10
  • 26
  • yes, it is 'parseerror'. But I checked my JSON and it is valid. What else can cause this error? – usp Apr 02 '13 at 19:24
  • Your callback function is not called by the server. The received payload should be something like callback_function([JSON_DATA]). check this link (http://en.wikipedia.org/wiki/JSONP) – Bechir Apr 02 '13 at 19:44
1

The returned code is not JSONP. it is simple JSON.

In jsonp the server must return the JSON objects as parameters of the function with the name provided as the callback parameter.

In your configuration, if the callback parameter that is sent to the server is 'example', the server must answer with

example( json code here )

and not just

json code here

as it does now.

With the $.ajax function you do not have to specify the callback function name on the client side, but the server must respect it.

david
  • 804
  • 7
  • 21
  • I have to use JSONP as I am getting the "Origin null is not allowed by Access-Control-Allow-Origin." error. – usp Apr 02 '13 at 19:35
  • I think the reason for my error was that I didn't 'host' web-page. I just opened with the browser. So, JSON works fine. Thanks for the help. – usp Apr 02 '13 at 19:41