Handling HTTP status Ajax response - javascript

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

Related

AJAX is not sending request

I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});

JQuery to validate url from another domain not working

I am kind of new to JQuery. My requirement is to validate a link from another domain. If success, then redirect (Open the page a new window) to that link, otherwise show alert.
What I tried in Jsfiddle are given below:
$.ajax({
url: "/user/login",
method: 'head',
error: function(){
alert('Failure');
},
success: function(){
alert("Success");
}
})
The above one succesfully validated the URL. But once I changed the url to http://www.google.com, it is not working. Code snippet is given below:
$.ajax({
url: "http://google.com",
method: 'head',
error: function(){
alert('Failure');
},
success: function(){
alert("Success");
}
})
Any idea why this is not working and is there any way to solve that? I just found out that cross domain validation is not supported in JQuery. Is it true?
<script>
var testUrl = "http://www.google1.com";
$.ajax({
url: testUrl,
dataType: 'jsonp',
crossDomain: true,
timeout: 5000,
complete: function( e, xhr, settings ) {
switch( e.status ) {
case 200:
window.open( testUrl );
break;
default:
alert( 'Not Valid' );
return false;
break;
}
}
});
</script>
Alternatively, I would send a AJAX request to an internal Server Side Script would then check using some server side methods, such as cURL/get_file_contents() for PHP.

404 and 401 errors in the ajax request

I am using jQuery's ajax method to submit an ajax request like this:
$.ajax({
type: "PUT",
url: someURL,
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json"
})
How can I add error handlers for the http status codes 401 and 404?
From the jQuery documentation, you can implement handlers for specific status code responses as options when calling .ajax():
$.ajax({
type: "PUT",
url: someURL,
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
statusCode: {
404: function() {
// handle the 404 response
},
401: function() {
// handle the 401 response
}
}
})
Look at the docs for goodness sake.
statusCode (default: {})
Type: PlainObject
An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.
(version added: 1.5)
It's really simple to find an answer if you look at the documentation that describes the behavior of a method.

How to handle ajax 201

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.

jquery ajax does not send request

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.

Categories