I'm not much of a javascript guy but I would like to implement error dialogs in this project I'm working on. I want to send a http header that the error function will catch and display the correct message. I've already tested the error function with an alert box and when I send a header 400, the error function is triggered.
Is it possible in JQuery or javascript to show different messages / dialogs based on the header code like 400 or 401? Based on that code then show the user the proper error message? I have about 4 or 5 messages that I need to show per error function
error:function(){
// call my dialog here
}
The statusCode option is available in jQuery 1.5+ for jQuery.ajax:
A map 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, they take the same parameters as the error callback.
Related
I am new to angular 10 and I am trying to make an http post to a PHP file as shown below
this.http.post(`${environment.server}/path/file.php`, {param1, param2})
.subscribe(
data => {
console.log(JSON.stringify(data));
},
error => {
console.log(error);
this.error = error;
});
The file is successfully called and returns the following JSON as displayed in the console response
{"Email":null,"school_year":2021,"academic_year":"2021"}
When I make the request I am immediately taken to the error state and all the console log is showing below only prints "OK"
console.log(error);
The two questions are the following
Why am getting to the error when the file is successfully returning JSON
Is there a way to get a more helpful error message than just OK
You will need to set the content type to application/json
You would be better off if you used a rest API rather than using php files. .NET Core or Node.JS would give you a better development experience.
It seems that your back-end PHP send the response with status code 400. It should be revised to 200 to get the data in response. When Status code is in Error range like 400, 401, 403 ... http Response will resolved in error or catch part.
In addition if you want just get data, it's better to use GET instead of POST.
I am trying to figure out that how can I handle different responses sent from PHP to AJAX differently (I am using toastr for nice message display on front end). Say someone tried to insert some value into the database and the value got inserted successfully, then i sent I message from PHP by
echo "Data inserted";
and this gets caught by ajax response and gets handled by
success: function(response) {
toastr.success(response);
}
But I want that, when PHP sends a message something like
echo "Unable to insert data";
My AJAX handles it as an error and I want to use toastr.danger() instead of toastr.success().
How can I handle this situation ?
In PHP, you can use the http_response_code() function to send the 400 HTTP status code:
http_response_code(400);
echo "Unable to insert data";
In jQuery, use the error callback to handle the 400 response:
error: function(response) {
toastr.danger(response);
}
As Jon Stirling said in comment, check HTTP status code (200: OK, 404: Not found, 500: Server error...), statusCode in $.ajax options.
Or use error in $.ajax options (opposed to success options).
Or (but not the best really), check for a word in your response with String.indexOf('yourWord')
Try to send this in php
header("HTTP/1.0 403 Forbidden");
exit 'Bad user name / password';
header('HTTP/1.1 500 Internal Server Error');
exit("Something went wrong when we tried to save your comment. Please try again later. Sorry for any inconvenience");
header('HTTP/1.1 400 Bad Request');
exit("This is a message about your invalid fields. Please correct before resubmitting.");
I know to get a response of a specific url by ajax method by :-
$.ajax({
url : myurl.com,
type : GET,
statusCode: {
404: function() {
alert ('failure');
}
200: function(){
alert ('success');
}
}
});
But, in my case when I hit the url, it triggers several other requests (as I see from the 'Network Panel' on Chrome Developer Options). And, I want to get the response of one of those requests generated.
Please tell how to do this. Or is there any method to get responses of all the network requests generated by hitting a url.
I need to capture 901 error codes in my header.jsp to handle ajax errors globally.
In browser console I am getting:
GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activity%20Report&_=1431351700771 901 (OK)
How can I capture and redirect on the basis of whether we got 901 error code or not?
you can use the ajax status code:
$.ajax({
statusCode: {
400: function() {
alert('400 status code! user error');
},
901: function() {
alert('error 901');
}
}
});
I am working on an e-commerce site and I need google sign-on it, so when a user creates his/her shopping list and click on the add to list button. I am able to send my data through the $.ajax() method, so what I exactly want is when the response from ajax method come it should redirect me to Login page if the user is not logged in, else it should save my object.
In the target endpoint of that .ajax() call, check your authentication, and if the user is not logged in, set the response header to - 401 Unauthorized.
Then in the .ajax() do this:
$.ajax(function() {
//.. your other ajax stuff..//
error: function(jqXHR, textStatus, errorThrown) {
// only redirect if user unauthorized - 'errorThrown' has text part of HTTP status header
if(errorThrown == "Unauthorized") {
window.location.href = "myloginpage.html";
}
}
});
The response header being set to 401 will trigger .ajax()'s error function, instead of the success function.
Edit:
Changed the error function to only redirect on Unauthorized
Also note, that if this is a cross-domain jsonp call, it won't work, as jsonp requests fail silently and don't trigger the error function
check in your response callback function and write your programming logic that you want
$.ajax({
'url':location,
'type':type,
'success':function(response){
/*write here your logic*/
},
'error':function(){
/*you code for error handling*/
}
});
to redirect window by javascript use
window.location.href = 'your location';
You can redirect to login page using window.location = 'yourlocation' in either success or error function of the response (depending upon what response you are gettig from server. If you are bringing the response code in header 401 error function will be executed other wise success).
but i think what you would like to have is take user back to the same page after login from which he started.
If you are interrested in this, you can use spring security for this. Its very easy to integrate if you are using spring already.
If you are not using spring you might look for some alternative for the same. Following links may help you
Spring Security Ajax login
http://java.dzone.com/articles/implementing-ajax
In jquery there is .post() method found to do this. In action page you can do whatever you want.