jQuery ajax error but the server is responding fine - javascript

I am trying to make request to server using jQuery ajax() but onResponse error block is being executed . The server response is working fine when the request is done from any other resources. This is my ajax:
$.ajax({
type:'post',
url: url,
data:{adminname: admin.ADMIN_NAME, adminID: admin.ADMIN_ID, modulename: moduleName },
dataType:'json',
success:function(data){
alert("hello world");
},
error:function(xhr, status, error) {
//when the response is returned this is being displayed
alert("error");
}
});
The request is being sent and even the data is being is updated but when the response is returned error block is being executed. There no errors on the server side. Where am I going wrong?

Related

Ajax Request sometimes causes `XHR failed loading: POST` error

I am trying to run a simple Ajax Request to pass a JSON object from my Javascript file to my Python file in Django. However half the time, I get the error XHR failed loading: POST when I run it as follows:
var csrf = $("[name=csrfmiddlewaretoken]").val()
$.ajax({
type: "POST",
url: "/fridge",
data: {
"fridgeitems": JSON.stringify(fridge),
"csrfmiddlewaretoken": csrf
},
dataType: "json",
timeout: 5000,
}).done(function(data) {
console.log(data.fridge);
}).fail(function(jqXHR, status) {
alert('Request could not complete' + status);
});
})
// rest of code
In my python file:
fridgeitems = request.POST['fridgeitems']
# do something with the data
response_data = json.dumps(fridgeitems)
return JsonResponse({"fridge": fridgeitems}})
I think what is happening is that when the Ajax request is placed the rest of the code runs, finishes and quits the function before ajax call has time to load. I have tried including timeout in my Ajax call however this appears to do nothing. How can I make the function wait for the Ajax call to finish?
Your problem is most likely that your request is timing out after a while of not getting response from the server. One likely cause is due to a slow network.
To handle this, do either or both of two things:
1. Handle the case where an request doesn't complete with the fail() method of the jqXHR object.
2. Include a timeout in the ajax request settings.
I illustrate using the combined strategy below:
var csrf = $("[name=csrfmiddlewaretoken]").val();
$.ajax({
method: "POST",
url: "/fridge",
data: {
"fridgeitems": JSON.stringify(fridge),
"csrfmiddlewaretoken": csrf,
},
dataType: "json",
timeout: 5000 // 5000ms
}).done(function(data) {
// is called if request is successful
console.log(data.fridge);
}).fail(function(jqXHR, status) {
// is called if request fails or timeout is reached
alert('Request could not complete: ' + status);
});
Notice, the use of the jQuery deferred objects methods: done() and fail() instead of sucess() and error(). The later is deprecated.

Error or fail not being reached when Ajax fails to fetch JSON

I am working on below Ajax code in JavaScript, I am trying to pop up a dialog box when the URL could not load the JSON properly the reason may be either expired token or incorrect token, in any case, I am expecting the code to hit the error or fail but it's not happening. When the URL could load the JSON successfully, success and complete blocks are being hit as expected but nothing is being hit when URL fails. I have tried to use async: false and tried to check with a boolean variable weHaveSuccess but console.log(weHaveSuccess); which is in the last line of the code is getting executing even before success/error is being executed and it seems to me like its still loading asynchronously. I would like to know why error block is not being hit when the JSON load from URL is getting failed.
My code
function checkUser(myURL, newAccessToken, weHaveSuccess) {
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: myURL + newAccessToken,
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
},
success: function (data) {
console.log("Hello 2 " + JSON.stringify(data));
weHaveSuccess = true;
console.log('Message from Success ' + weHaveSuccess);
},
complete: function () {
console.log('Message from Complete ' + weHaveSuccess);
}
}).done(function (data) {
alert("Success");
console.log(data);
}).fail(function (data) {
console.log(data);
alert("Failed");
}).always(function () {
alert("In Always");
});
console.log(weHaveSuccess);
}
Thanks in advance!
AJAX requests are asynchronous. It takes time for a remote request to be made and responded to. You will have to write your post-response code within the success function or call another function from there, not within the same scope as where the call is initiated.
I am taking a bit of a guess here about what your server returns on failure. An AJAX request success means simply that a 200 OK response was received, without any consideration of the contents of the data. If an error is simply a change in the data you will need do one of the following to show an error:
Have the server set a status code header on failure, perhaps 400 Bad Request.
In the success function look within your data for whatever error response you are expecting and trigger the alert() there.
First of all the console.log(weHaveSuccess); fires first, because the $.ajax() is asynchronous while console.log is not so ajax will be triggered and return the promise when finishes, but the browser will continue with the script.
In the jQuery ajax docs says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
It's hard to debug without seeing the response, maybe you can add some info from the network or a URL?
How about if you try the following:
Add the jsonp setting to your $.ajax() function for the callback that will handle the response and console.log there:
function myCallback(data) {
console.log(data);
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: myCallback,
...

response error from ajax http post crossdomain request with json

I am using asp.net and on client side in javascript and I try to make an ajax HTTP request:
$.ajax({
type: 'POST',
url: url,
crossDomain: true,
data: trip,
dataType: 'json',
success: function (responseData, textStatus) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
on the other side i have an azurecloud project and this method (c#):
[ActionName("test")]
[HttpPost]
public IHttpActionResult Test([FromBody] SetTripRequestEntity trip)
{
return Ok("year it works!");
}
If I run the code, the server jumps into the c# method and the trip has the correct object, so everything is fine.
But after he returns Ok("year it works!"); on the javascript side he runs into the error function:
responseData is an object with nulls and 0 parameters,
textStatus is "error" (really only "error" not more)
errorThrown is ""
I don't understand why he does not go to the success function.
I have tried to make the request in fiddler2 and there I got the right answer.
So the problem is at the javascript (ajax) side.
does somebody know how to run it?
Thanks a lot!

jQuery ajax - Absolute URL's and error handling

Is it possible to catch the HTTP errors (like 404, 500, 504 etc) when we call an external webservice by specifying an absolute url?. (like setting the url: attribute of $.ajax call to have a url value as http://api.geonames.org/findNearbyPostalCodes.
Right now I'm unable to receive any errors although firebug is catching them and showing it in the console.
Can someone help?
Here is my code.
$.ajax({
type: 'GET',
url: "http://api.geonames.org/findNearbyPostalCodes",
data: '{"lat":47,"lng":"9","username":"demo"}',
dataType: 'json',
cache:false,
async:false,
statusCode:{
404: function(){
alert('Page not found');
},
500: function(){
alert('Page not found');
},
504: function(){
alert('Unknown host');
}
},
success: function(data){
alert(data);
}
error: function (xhr, exception, thrownError)
{
alert(xhr.status);
}
});
No, it is not possible with cross-domain (external) requests using only client-side code. This is because cross-domain requests rely on JSONP - ie, injecting a script tag that loads code from an external source. Unfortunately, the <script> element does not have anything like an onerror event.
You can handle errors with same-domain requests because these typically use XMLHttpRequest, which returns a lot of useful information like status codes and response headers.
Your best bet would be to use your local server as a proxy.
If using an absolute URL causes the domain to be different from the domain of your page (cross-domain request), then the only way to successfully execute an ajax call is to use JSONP which will cause the ajax library to use <script> tags for the cross-domain request instead of the more typical XMLHttpRequest used for same-domain requests.
You will not be able to intercept any sort of status codes from the loading of the cross-domain <script> tag.
In your case, you cannot check the status code (assuming you're not making the request from api.geonames.org).
jQuery will always return a "0" as the status if the request is cross-domain:
$.ajax({
type: 'GET',
url: 'http://someotherdomain.com/api/query',
dataType: 'json',
data: '{"first": 1, "second": 2}',
complete: function(response) { // the 'response' object has the status code
if (response.status == '200') {
// do something on success
} else if (response.status == '0') {
alert('Your request is cross-domain');
}
}
});
If the request happens to be within the same domain, you'll get a valid status code that you can check (the complete attribute of the $.ajax() function will run after any success or failure callbacks are run).

jQuery.ajax() sends POST requests as GET in a Chrome extension

I'm building a small Chrome extension that must send messages through a POST http request to a server in my company network, and I'm using jQuery 1.4.1 to speed up the development of the javascript part.
I have this code to send the request:
function send() {
$.ajax({
url: "http://mycompany.com/update",
method: "POST",
data: {status: "sometest", in_reply_to_status_id: "anId"},
success: function(data, textStatus) {
console.log("success");
console.log(data);
console.log(textStatus);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error");
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
},
complete: function(XMLHttpRequest, textStatus) {
console.log("complete");
}
});
}
The request done this way fails, in the Chrome log I see that the server responds with a http status 400 and with the text "This methods requires POST".
If I change to code above with this:
function send() {
$.post("http://sunshine.emerasoft.com/statusnet/api/statuses/update.xml", {status: "sometext", in_reply_to_status_id: "anId"}, function(data) {
console.log(data)
});
}
everything works fine, the http status is 200 and server side I can see that the data I sent is correctly saved.
I need to use the full $.ajax() method because I need to do some work in case of success or failure, and some other when the request is complete, so $.post() is not enough.
Am I doing something wrong calling $.ajax(), or there is an issue of some kind, maybe because I am in the xontext of a Chrome extension?
Thanks
I believe the $.ajax() function takes a 'type' option, not a 'method' option.
The default type is GET.

Categories

Resources