If I make a jquery AJAX request which is succesful I get back my JSON data. However, If I make a request and I get somthing other than a 200 response code back, I cannot get back the data in the Jquery call back. I need the data as it has a description about the data.
success: function (data, tst, xhr) {
$.log('XHR OK');
},
error: function (xhr, tst, err) {
$.log('XHR ERROR ' + XMLHttpRequest.status);
},
Any ideas?
Thanks
In the:
error: function (xhr, tst, err) {
$.log('XHR ERROR ' + XMLHttpRequest.status);
},
you can use
error: function (XMLHttpRequest, textStatus, errorThrown) {
$.log('XHR ERROR ' + XMLHttpRequest.status);
return JSON.parse(XMLHttpRequest.responseText);
},
to get the JSON response in in event of an error.
XMLHttpRequest.responseText
Cheers.
Try the jQuery JSONP plugin. It adds an error callback to a JSON request like so:
$.jsonp({
url: "Your URL",
data: {data: "Some Data"},
dataType: 'jsonp',
timeout: 2000,
success: function(data, status) {
// Do something with data here
},
error: function(xhr, text_status){
// Handle the server error
}
});
It does this using a timeout to wait for the server. Unfortunately, there is no other way of telling if the server response with something other than a 200 response.
Related
The JSON response body of the HTTP request is being distorted on the server side. It has one key and its element is an array. This is my HTTP request using jQuery ajax:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
When I print JSON.stringify(event_arr) to console, this is what it looks like:
{"results": [{"event_client": "name1","event_date": "date1"}, {"event_client": "name2", "event_date": "date2"}]}
Then, on the server side, here are my various attempts at understanding the response body and playing around with the JSON format:
// returns [object, Object], cannot be passed into JSON.parse
console.log(request.body);
var temp = JSON.stringify(request.body);
var temp2 = JSON.parse(temp);
// prints {"{\"results\":":{"{\"event_name\":\"name1\",\"event_date\":\"date1\"},{\"event_name\":\"name2\",\"event_date\":\"date2\"}":""}}
console.log(temp);
// prints { '{"results":': { '{"event_name":"name1","event_date":"date1"},{"event_name":"name2","event_date":"date2"}': '' } }
console.log(temp2);
The JSON.stringify() that was called in my dbInsert() seems to mess up how the JSON is read, and I don't how to work around this internal formatting error!
You need to set: contentType: "application/json", in your $.ajax({}) function.
Something like this:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
contentType: "application/json",
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
}
In JQuery AJAX while calling a REST API, As per the functionality the negative use cases needs to be logged.
In the chrome console this can be seen
net::ERR_ADDRESS_UNREACHABLE
net::ERR_NETWORK_CHANGED
net::ERR_NAME_NOT_RESOLVED
how to capture these exact errors in the error callback or any other means
The JQuery AJAX Code is
$.ajax({
type: 'GET',
url: <my url>,
contentType:'application/json',
dataType:'text',
beforeSend: function (xhr) { },
data: "",
success: function (responseData, textStatus, jqXHR) {
//success code
},
error: function (responseData, textStatus, errorThrown) {
console.log(arguments);
//here I need to capture the exact network error
}
I am trying to call external api in php using ajax-jquery.
But getting error
"No 'Access-Control-Allow-Origin' header is present"
API doesn't support "JSONP". Any work around to make it work.
=============================
Code Snippet I tried.
$.ajax({
url: 'http://currency-api.appspot.com/api/CAD/EUR.json?key=b4a547e6aa86da2ced5278e3d21b4ad95e011ef8',
dataType: 'JSON',
headers: { 'Access-Control-Allow-Origin': '*' },
async: true,
type: 'GET',
success: function (data, textStatus, jqXHR) {
console.log("---------SUCCESS-------------");
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("---------ERROR-------------");
console.log("** textStatus :" + textStatus);
console.log("** errorThrown :" + errorThrown);
},
complete: function(jqXHR, textStatus) {
console.log("---------COMPLETE-------------");
console.log("** textStatus :" + textStatus);
}
});
}
=============================
I appreciate your prompt help.
Thanks,
SAV.
sending isn't the problem, it's receiving, your browser won't let the AJAX call use the data because it came from another site. you need to add the header to the page, not the AJAX call.
You will need a proxy hosted on the same domain as your script.
Then you'll request the distant API through it.
A simple proxy in php.
When making a ajax call see example below success does gets a 201 status retuned. How do you handle these better i.e. 200, 201 within the success function?
$.ajax({
type: "POST",
dataType: "json",
url: "http://api.domain.com/sms",
data: {
// Send value in mobile input field.
mobile: $("#mobile").val(),
},
// On successful AJAX call do the following.
success: function(data) {
$('#messageText').text('SMS successfully sent');
},
error: function(jqXhr) {
data = JSON.parse(jqXhr.responseText);
}
});
Use the statusCode object:
var handle200 = function(data, textStatus, jqXHR) {
alert('200'); // success codes have the success signature
};
var handle201 = function(data, textStatus, jqXHR) {
alert('201'); // success codes have the success signature
// test it if you are in doubt:
console.log(data);
console.log(textStatus);
console.log(jqXHR);
};
var handle404 = function(jqXHR, textStatus, errorThrown) {
alert('404'); // failing codes have the error signature
});
var request = $.ajax({
type: 'POST',
url: '/myresource/posttarget',
data: { name: 'john' },
statusCode: {
200: handle200,
201: handle201,
404: handle404
}
});
This is an old question but I'd like to comment anyway.
I had the same problem and one thing that solved it for me was leaving the "dataType" unsetted. When you do this jQuery will try to guess the data type the server is returning and will not throw an error when your server returns a 201 with no content.
Hope it helps.
We had a similar problem; Looking at the jquery 1.9 source, a 201 status code expects content. If there is no content (or of the wrong content type) returned with the 201, then the fail callback is invoked.
Data inserted successful but jquery still returning error
The answer here appears to be a work around you can use for now. However, if you're using cross-domain, AJAX has some issues with that. Check out this SOF thread on it:
Problems Reading the HTTP Status/Error Code from jQuery AJAX
Instead of
ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);
I used
ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);
Where detailVO is my object to rutrun in case of success. Then in browser I got response in success function.
I have got this function:
var current_url=window.location.href;
$.ajax({url: 'http://api.apps.com/html/'+appid,
data: {url:current_url},
dataType: 'jsonp',
timeout: 10000,
jsonp: "set_url_target",
success: function(data) { console.log(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
}).done(function() {
console.log("Message has been complete!!");
});
What I want is to trigger this function on http://api.apps.com/html/ (Note it is a different domain).
function set_url_target(url){
console.log("Url has been recieved: "+url);
}
So far the set_url_target isnt being triggered, and I get nothing being printed to the console, no error or nothing.. why?
if the external application isnt under your control I am afraid you cannot do much as you need to update the response that is sent by the server to the client side to use JSONP successfully..
thus you have two options:
a) make the call on server side in your application and return it to the client
b) alternatively to entirely make it client side you could use something like yahoo pipes or other services which transform the json response to valid jsonp response.
here is an example on how to do it using yahoo pipes: https://gist.github.com/316660
I am not sure about the license, do check upon them and if there are and associated API/Bandwidth costs. Let me know how it works out for you..
Try this, note the jsonp and jsonpCallback attributes
var current_url=window.location.href;
$.ajax({url: 'http://api.apps.com/html/'+appid,
data: {url:current_url},
dataType: 'jsonp',
timeout: 10000,
jsonp : false,
jsonpCallback: "set_url_target",
success: function(data) { console.log(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
}).done(function() {
console.log("Message has been complete!!");
});
For more info on this, AJAX