jQuery AJAX request getting response but no callbacks are fired - javascript

I have code as such:
$.ajax({
method: "GET",
url: page,
dataType: 'html',
data:data,
success: function(data){
console.log(data);
},
error: function(){
console.log('error');
}
});
Using either Chrome or Firefox's debugger I can see that the request is successful with a response of 200 OK and the response contains the expected data.
My problem is, however, that no callbacks fire whatsoever. "Success" does not fire nor does "Error". Furthermore, no deferred methods fire either, such as "done", "then", or "always".
I've been trying to trouble shoot this for the past few hours to no avail. I'm at a total loss. I've also tried using methods such as "$.get" with the same result.
In short, I'm getting the response, but the code in jQuery is not firing any callbacks and all without any visible errors in the console.

One thing I see wrong in your code is that:
method: "GET",
should be:
type: "GET",
I don't see any documented property for method in the jQuery doc. The type property is supposed to default to "GET" so this may not be the only thing wrong here.
In addition, there are cases where the error callback will not be called even if the ajax call fails (in cross-domain requests). From the jQuery doc for the error callback:
This handler is not called for cross-domain script and cross-domain JSONP requests.
This is because jQuery is expecting the server to send back a particular form of javascript and if the server doesn't do what is expected, then jQuery never knows when the request comes back and can't process it.
In these cases, you often have to figure out what might be going wrong from looking at the network trace in the debugger.
Other things to check to make sure you aren't accidentally cross domain:
Make sure the domain/subdomain are exactly the same between ajax call and the page. For example, one common mistake is for one to have www. on it and the other not.
Make both page and ajax URL are both same http or https.
If using a non-standard port number, make sure both page and ajax URL are using the same port.

The following code works. Also note that AJAX will not work with cross site scripting.
If you want to get the error you can print the "errorThrown"
<script>
$(document).ready(function () {
$('#getLink').on("click", function () {
var url = $("#myUrl");
alert(url.val());
$.ajax({
type: "GET",
url: url.val(),
dataType: 'html',
success: function (data, textStatus, xhr) {
$("#data").text(textStatus);
},
error: function (data,textStatus, errorThrown){
$("#data").text(errorThrown);
}
});
});
});
</script>
<input id="myUrl" name="myURL" type="text" value="http://localhost:35460/Home/TestPage.cshtml" />
<input type="button" value="getLink" id="getLink">
<span id="data"></span>

Related

Jquery ajax response not calling Success method

I am pretty much new to ajax and working on jquery ajax request. Ajax callback is not calling success method. Interaction is between cross-site domains.
My AJAX request looks like
$.ajax({
timeout: 20000,
url: 'test.com',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
} });
There are no errors in this call.
This ajax request is not calling success function.Request is returning json data. it's just success method is not getting called.
This ajax request is not calling success function.
Get request is getting fired successfully. I can even trace the response in fiddler with 200 http response.For some reason success method is not getting called.
it's returning json object, which I've traced in fiddler
You're telling jQuery to expect a JSONP response, so it is trying to execute the JSON document as if it were a JavaScript script (because that is what JSONP is). This fails because it is not JSONP.
Either return JSONP instead of JSON or (assuming the server returns the correct Content-Type) remove dataType: 'jsonp',.
ok... I came here with the same problem... and when I read that specifying datatype:jsonp never calls success as a callback per #mondjunge from a comment above, it started me thinking about some behavior I saw earlier from my code and that maybe datatype:json might have the same behavior for what ever reason here too.
So after reading this page I took out my datatype declaration from my ajax request and my servlet returned the proper data payload, returned a 200, and jquery called the success function finally and modified my DOM.
All those steps happened except the last one until I removed my datatype from my ajax call. NOT what I was expecting!
Hopefully someone else can shed some light on why this happens... for now at least the few that don't lose their minds to this issue that find this post can do this in the mean time.
Check if your ajax is executed
Check it's status. If response code is != 200, than you should add error method also, for error handling.
Try this:
$.ajax({
timeout: 20000,
url: 'test.com',
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
});

Ajax response with JSONP, can see result cannot use it

I have the following javascript:
jQuery(document).ready( function($) {
var id = "123";
var api = "example.com:8999/".concat(id)
$.ajax({
url : api,
type: 'GET',
dataType: 'jsonp',
// jsonpCallback: "localcallback",
success: function (data) { alert('success'); }
})
});
I can see the response in chrome dev tools, but the alert isn't getting called. Ultimately I need to work with this response to set the value of a div.
Image of chrome tools:
Thanks
EDIT: Put 'POST', was using 'GET', still not working. Also, I think I'd prefer "mom and pop" json, but due to CORS and the fact I'm not good with the web and am just trying to hack this together.
Your server is not returning JSONP. It's returning plain JSON. If you specify JSONP, then the server must explicitly create a JSONP formatted response or the ajax response will not be received and processed properly.
FYI, a JSONP request is sent via a script tag (that's how it gets around the same-origin limitation for cross domain requests) and the response has to be formatted as a script that calls a function and passed the requested data to that function. You can read about how JSONP works here.
Just make your ajax call without specifying the 'dataType' attribute, then control should come back to your success callback if your ajax call completes successfully.
FYI: jQuery will try to find the response data type based on the MIME type of that response.
Example:
$( function() {
$.ajax({
url :"http://example.com:8999/123",
type: 'GET',
success: function (data) {
console.log(data); // Prints the response on console
alert('success');
}
})
});
If you want to make this call only with JSONP then it would be better to share the reason with us, so that we can suggest a better solution if possible.

Call similar to $.get in $.ajax

I have the following code:
$.get(url, {}, checkResponse)
And the following function:
function checkResponse(content) {}
The parameter "content" here is the result of the "get". I wanted to implement $.ajax to able to wait for the process to complete before it jump to the next chunk of code. I tried the following code but it didn't work.
$.ajax({
async: false,
type: 'GET',
url: url,
success: function (data) {
alert(data.toString());
checkResponse(data);
},
error: function (data) {
alert("error");
}
});
Here's what happened, the alert for the data.toString() gives empty string value while it should give me the url page content, and after it hits the alert it jumps to the error section and displays the alert "error".
According to the discussion in the comments section you are trying to send cross domain AJAX calls to arbitrary urls on the internet. Due to the same origin policy restriction that's built into the browsers this is not possible.
Possible workarounds involve using JSONP or CORS but since you will be sending requests to arbitrary urls that you have no control over they might not be an option. The only viable solution in this case is for you to write a server side script that you will host on your domain acting as a bridge. This script will receive an url as parameter and send an HTTP request to this url in order to retrieve the result. Then it will simply return the result back to the response. Finally you will send an AJAX request to your own server side script.

JSONP request returning error: "Uncaught SyntaxError: Unexpected token :"

So I'm trying to make a request to the Stack Exchange API with the following jQuery code:
$.ajax({
type: 'POST',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
But when I open the file on my machine, in either FireFox or Chrome, and make the request, I get this error:
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
Uh Oh!
I don't have a clue what's going on. I know the Stack Exchange API Gzips its responses, would this cause any trouble?
You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback, you need to pass a jsonp parameter.
Furthermore, you can't do POST with JSONP.
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp'
});
It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy).
There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function.
The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead.
Try this URL: http://api.stackoverflow.com/1.1/stats?jsonp=callme
"callme" is the name of your callback function - in your GLOBAL NAMESPACE (window object).
By the way, if you are running Firefox and have the JSONView add-on installed you can test the above URL (and yours for comparison) directly.
Result from calling the URL:
callme({
"statistics": [
...
]
})

Calling a webservice using JQuery

I am using this code from http://www.joe-stevens.com/2010/01/04/using-jquery-to-make-ajax-calls-to-an-asmx-web-service-using-asp-net/
function callWebService(address) {
var result;
$("#result").addClass("loading");
$.ajax({
type: "POST",
url: address,
data: "{}",contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
}
function Success(data, status) {
$("#result").removeClass("loading");
$("#result").html(data.d);
alert("Success");
}
function Error(request, status, error) {
$("#result").removeClass("loading");
$("#result").html(request.statusText);
alert("Error");
}
I don't understand what is wrong with this code. It keeps returning "Error"
Also make sure that the service URL that you're trying to access is in the same domain as your site. AJAX calls won't succeed if you cross domains, since browsers subject AJAX calls to the same domain policy. Can you also include the URL you're trying to access?
If you're trying to access a resource at a different domain, you may want to consider a JSONP request instead. See the jQuery AJAX documentation for a discussion of how to use JSONP.
I think if you combine knowing the URL you're trying to access along with Justin and mohlsen's suggestions, I think we can help.
Your code looks fine at first glance.
I recommend you use FireBug to attempt to isolate the problem further, as it will allow you to see the actual HTTP requests, POSTed data, etc...
A few suggestions based on some code I have doing this. But as others have said, make sure to manually look at the data going out and coming back. Your link references asp.net webservice, is that what you are calling since you didn't mention it.
Make sure the "address" url is of the form /location/page.asmx/methodname
You might need to pass the data to the success method in the call
success: function(msg) {
//msg is a json object, .d is the data field returned by asp.net
if (msg.d.length > 0)
ProcessData(msg.d);
else
HandleError('No data was returned.');
},
error: function() {
HandleError('There was a problem calling the webservice.');
}

Categories

Resources