I have the following code to make a jsonp call.
var contacts;
$.ajax({
url: "http://localhost:51973/Service1/GetContacts",
type: "GET",
async: false,
data: { companyName: company },
dataType: "jsonp",
success: function(data) {
contacts = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error " + XMLHttpRequest.statusText);
}
});
but for whatever reason I get the contacts as undefined. I inspected the traffic using fiddler and I found the it was getting the following response.
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 09 Apr 2012 14:52:33 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 100
Cache-Control: private
Content-Type: application/x-javascript
Connection: Close
jQuery17107471185381512466_1333983153278([{"Email":"john@test.com","Name":"Test Company"}]);
so why is contacts variable not being set properly?
I would guess that you are trying to use the contacts variable right after the ajax call. You cannot do that. The ajax call is asychronous and thus completes sometime AFTER the ajax call completes. When it completes, the success handler is called. You need to put any code or any function calls that actually use the contacts information inside the success handler. This is asynchronous programming and you have to code it differently.