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.
Related
Suppose I am trying to fetch page which throws a 404 not found response yet shows an html page. I want to get html elements of that page using jQuery.
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
console.log($(data).find('#reviews .card').text());
},
error: function(data) {
console.log($(data).find('.not-found').text());
}
});
I get this message in console window
GET http://example.com/page/2/ 404 ()
Suppose I wanna grab the title from the page which says "Page does not exist." and the JSON object data returned between the <script> </script> of the html of the page, how should I do it?
do you mean this?
jQuery Ajax error handling, show custom exception messages
success: function(){
...
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr); // I believe this returns an object
console.log(xhr.statusText); //"Not Found"
console.log(xhr.status); //404
},
});
I too had this problem:
error: function (err) {
console.log(err); // This will throw the whole error.
console.log(err.response); // This will throw the object you want to modify
console.log(error.response.status); // This will throw the status code you want!
},
Hope this works!
As stated by #RoryMcCrossan I used responseText and rewrote the code again to something like this.
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
var html = $(data);
console.log(html.find('#reviews .card').text());
},
error: function(data) {
var html = $(data.responseText)
console.log(html.find('.not-found').text());
}
});
I have some ajax that's returning a 403 error message but when it does, the click() function that was associated with the ajax call no longer works. I don't append or add any HTML before or after the ajax call, and if the ajax doesn't receive a 403 error, there are no problems. It's just simply if I receive a 403 error from the ajax POST, then the click() breaks. How can I fix this?
Here is my code:
$( "#add_comment" ).on('click', null, function() {
var data = {token:"{{ Session::token() }}", comment:$('#game_comment_form form textarea').val() };
$.ajax({
type: "POST",
dataType: 'json',
url: '/game/comment/{{$game->id}}',
data: data,
success: function(data){
alert("Success");
},
statusCode: {
403: function() {
alert( "Forbidden" );
}
},
error: function(e){
alert("Error");
console.log(e);
}
});
return false;
});
Why dont you try $.post(); method ?
like this...
$.post('/game/comment/{{$game->id}}',data,function(data){
alert("Success");
}).done(function(data, textStatus, jqXHR) {
// called on success
}).fail(function(jqXHR, textStatus, errorThrown) {
// called on failure
}).always(function() {
// called in both cases
});
Turns out I was completely overlooking the fact that I manually disable the input button and just simply forgot to re-enable it after the 403. I was going to delete this but hopefully someone else possibly realizes their simple mistake as I have and this helps them out.
I'm using the following code to get the dataa from the server:
$.getJSON('http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod?callback=?', dd, function (data) {
alert(data);
});
From the server, I'm sending the byte array as response.
In firebug, in Net > Response tab, I get:
jQuery19101878696953793153_1365677709012([67,37,94,38,42,44,69,67,71,32,97,116,116,97,99,104,101,100,32,102,111,114,32,112,97,116]);
Also in Net > JSON tab, I get data with several keys.
But how to get the data at alert(data);; so that I process on that data.
I don't know, how this thing works.
Edit:
I tried this different approach:
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/javascript",
data: dd,
crossDomain: true,
url: "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function (data) {
alert(JSON.parse(data));
},
complete: function (request, textStatus) { //for additional info
alert(request.responseText);
alert(textStatus);
},
error: function(request, textStatus, errorThrown) {
alert(textStatus);
}
});
But I got: parseerror as alert.
From looking at the docs (I haven't tried this) you need to explicitly tell jQuery that you're making a JSONP call that will invoke the function that's returned. Something like this:-
$.ajax({
type : "GET",
dataType : "jsonp",
url : "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function(data){
alert(data);
}
});
Function you are looking for is JSON.parse. Please try this code :
$.post("YouURL", { 'ParameterName': paramvalue }, function (Data) {
var data = JSON.parse(data);
});
Your response is a function call. If u define function name with name jQuery19101878696953793153_1365677709012 you can process the 'data' else from your server just send the json as a response to $.getJSON's callback to work
The problem was the data was very huge. I was sending array of around 10,00,000+ bytes.
So instead I divided it into list of bytes (each having 1000 bytes) & then sent as response.
I don't know if this is the best solution, but it solved my problem.
BTW, thanks to all for helping me.
I am attempting to integrate the Instapaper Simple API into something but I am struggling to understand how to handle the response that the API sends back in Javascript. The article is adding to Instapaper just fine so I know that the submission is working just not my response handlers.
This is the code I have so far and I'm guessing that the success function is not the correct way of handling the response.
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function( data, status ) {
alert("yay");
},
error: function(status) {
alert("oh noes");
}
});
return false;
Instapaper returns a 201 when the article has been added. I can see that in the Google Chrome Network tool that the GET returned a 201 status. Just wondering how I handle that status within the code above.
Thanks.
Edit
When I click the link to activate the code below it pops up the alter under the error function right now even though it has worked.
jQuery.ajax() provides statusCode map for such purposes:
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
statusCode: {
200: function( data ) {
alert("yay");
},
201: function( data ) {
}
},
error: function(status) {
alert("oh noes");
}
});
http://api.jquery.com/jQuery.ajax/
$.ajax({
statusCode: {
201: function() {
alert("201!");
}
}
});
this should work with any http status code
I have a problem with the following code.
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: 'sendMail.php',
type : "post",
data: sendJson,
success: function(data){
alert("Comanda dumneavoastra a fost trimisa");
}
});
Seems like data is not sent.... any idea why?
Ok... I know nothing is sent because I monitor requests with firebug.
I get no errors, nothing in console. Checked if it is activated, it is.
Here's what I meant with my comment:
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
Note that the ajax request has an error callback now. All requests should have an error callback so you can easily identify when errors are happening (as you've seen, firebug doesn't catch everything).
Another thing that I find helpful sometimes is StatusCodes:
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
statusCode: {
404: function() {
/*implementation for HTTP Status 404 (Not Found) goes here*/
},
401: function() {
/*implementation for HTTP Status 401 (Unauthorized) goes here*/
}
},
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
This will execute a function when a specific status code is returned by the server (404 and 401 in this snippet) and you can have a specific handler for the status codes you need.
You can find more about this here.