404 and 401 errors in the ajax request - javascript

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.

Related

Ajax request returns 200 but an fail event is fired instead of done

This is my ajax code, I have given data type as JSON. I receive the success response with code 200, But my ajax fail event is fired.
$.ajax({
url: 'API URL',
type: 'post',
dataType: 'JSON',
data: JSON.stringify(result)
}).done(function(response) {
console.log(response);
})
.fail(function(response) {
console.log("error");
});
By the way the response I received is of type JSON only, I have checked the headers.

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 ajax put request returns 400 error

The following ajax is being responded with a 400 error (bad request):
var jsonData = JSON.stringify({"DeliveryKey":"37507","Produkttyp":"ES 95 120","Abgabemenge":"12","Bonnummer":"","Vorpeilung":"12","Gesamtangabe":"24","NachpeilungVolume":"","PumpenstandVolume":""});
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
processData: false,
url: rootURL + 'allproducts/product/' + deliveryKey, // jsonObj.DeliveryKey
data: jsonData,
success: function(data){
alert("Data PUT-Request successfully!");
},
error: function(){
alert("Fehler in der Methode putProduktInDatabase()");
}
});
Here is the consuming sides code:
#Path("/allproducts")
public class ProduktModellResource {
ProduktModellDAO produktModellDAO = new ProduktModellDAO();
#PUT #Path("product/{deliveryKey}")
#Consumes({MediaType.APPLICATION_JSON})
public boolean putProduktInDatabase(ProduktModell produkt)
{
return produktModellDAO.putProduktInDatabase(produkt);
}
}
and here is the screenshot of the requests header in Google Chrome:
What am I doing wrong?
UPDATE:
On the server side I return "true" or "false" depending on whether the desired function was called or an exception has been thrown. Is that allowed or should I response only with a JSON?
From official Jquery site
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request
methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
You better do not use PUT type or... "you gonna have a bad time" ! :)

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Handling HTTP status Ajax response

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

Categories