Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with jQuery, ajax, and jsonp

I am using jsonp and ajax to access a web service on another server. Here's the jQuery:

$.ajax({
  type: 'GET',
  url: wsurl + 'callback=?',
  dataType: 'jsonp',
  crossDomain: true,
  error: function(data) {
    console.log('error', data);
  },
  success: function(data) {
    console.log('success', data);
  },
  complete: function() {
    console.log('done');
  }
});

The issue is that the error callback is being called. It gives me this wonderfully helpful information:

{
  readyState: 4,
  status: 200,
  statusText: "success"
}

And here is the json file I am calling:

{
  "id": 0,
  "room_number": "0",
  "first_name": "Admin",
  "last_name": "Istrator",
  "password": "",
  "salutation": "Mr.",
  "telephone": "",
  "email": "",
  "description": "admin",
  "checkin_date": 915797106000,
  "checkout_date": 4071557106000,
  "last_login_date": 947333106000,
  "active_status": true,
  "created_date": 915797106000,
  "created_by": 0,
  "reference_id": ""
}

I tried using the getJSON jQuery method first, with the same result. Thought I'd try the base ajax method, since it has a bit more control, but as you can see, no luck. So, notice anything I'm doing wrong? Have any idea why it is throwing an error and giving me a successful value for the statusText property?

EDIT

Alright, I added some options to the ajax call, and removed the callback param from the url. Here's the new ajax call:

  $.ajax({
    type: 'GET',
    url: wsurl,
    dataType: 'jsonp',
    crossDomain: true,
    error: function(xhr, textStatus, errorThrown) {
      console.log('textStatus: ' + textStatus);
    },
    success: function(data) {
      console.log('success');
      console.log(data);
    }
  });

I'm getting a new error, which is good I suppose, but still not working. Difference is that the textStatus is now "parsererror". The console is also throwing a syntax error on line one of the json file:

Uncaught SyntaxError: Unexpected token :

Ideas?

like image 738
Zachary Nicoll Avatar asked Nov 13 '22 10:11

Zachary Nicoll


1 Answers

Okay a couple of things jump out at me:

$.ajax({
  type: 'GET',
  #You do not need to append the callback as you have jsonp configured it will  do it    
  #automatically append the callback=<auto generated name>
  url: wsurl, 
  dataType: 'jsonp',
  crossDomain: true,
  error: function(data) {
    console.log('error', data);
  },
  success: function(data) {
    console.log('success', data);
  },
  complete: function() {
    console.log('done');
  }
});

Also your return does not to appear to be wrapped in a function which is required for jsonp to work.

<auto generated name>({ json object })

The callback function will be named by jquery automatically. So you need a service that will take in a callback parameter and return a json object with padding.

like image 168
Jamie Avatar answered Nov 16 '22 02:11

Jamie