How to handle responses sent from PHP differently in AJAX - javascript

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.");

Related

Angular 10 subscribe is failing to post with error code OK(and no other errors shown)

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.

how to notify client that reCaptcha is successful

Hello i have simple form where i have google reCaptcha v2 and when user submits form i am validating recaptcha but i also send email to user inputted email and i need to send status 200 two times here is first time where i need to send it
request(verifyURL, (err, res, body)=>{
body = JSON.parse(body);
if(body.success !== undefined && !body.success){
return res.status(409).send({
success: false,
message: 'დადასტურება ვერ ვოხერხდა'
})
}
return res.status(200).send({success: true})
})
so if i send status code 200 and use return statement, won't it cause
Can't set headers after they are sent
error?
if it will how can i fix it?
Thank you!
You cannot send multiple response for a single request. You can go with either:
1. Send the mail in the same controller, and when its done successfully, then only send the response back to client. Your response will be based on both factors ie. captcha validation and email sent response
or 2. if you don't wanna wait for the email process.. Just send response once your captcha is verified.. and keep the mail process execution in background. In this case you need to remove the return keyword or else your request will end there and mail process won't execute.
However, I'll suggest you to go with the first approach. Hope this helps :)

How to handle ajax call when there is no response from the server

I have an ajax call for some data (using jQuery). after the user clicks "submit" (and the ajax call has been sent) I am displaying a "Please wait..." message that disables everything until the request returns (so the user won't double click or click other things and mess things up).
It works great when there is any kind of error - the "Please wait..." disappears and I am displaying the user what went wrong.
But what happens if the server don't return me anything back because of communication error?
The solution I found for that is to set a timeout of 10 seconds for the "Please wait.." message that after that time it disappears and displays and error that "The communication failed". I assume that if the server didn't respond after 10 seconds then it will not respond at all - but that it false assumption.
The problem is - how can I be sure that after 20 seconds the server won't return something back? The scenario that might happen is that the user click submits --> 10 seconds later he get an error message --> 5 seconds later server response and confuses the user
How do I make sure that after I hide the "Please wait.." message nothing will pop up from the server?
when you send a request to a server. a connection is opened and its kept open unless the server responds.
1.if due to some error on the server side it cannot respond then a response code of 5xx is sent back generally (503)
2.if due to some connection issues the connection is terminated prematurely then also jquery would take that as an error.
1.so if you wanna wait for the server to send a request or connection termination (which ever occurs earlier) then u can use the completed option in the jquery ajax.
2.and if you are in a condition in which server isnt responding even after 20 secs and you think that it should have responded by now use timeout.
3.finally if your problem is that you are using some kind of customized(hand made http server) which doesn't end a request even if it encounters some error then atleast customize it enough so that it sends back some response code(because this is HTTP model of request and response)
You can handle something like this
if ( request.readyState == 4 ){ // 4 is "complete"
if ( request.status == 200 ){
// HTTP OK, carry out your normal Ajax processing
// ...
}else{
// something went wrong, report the error
error( "HTTP "+request.status+". An error was »
encountered: "+ request.statusText );
}
}
(or)
$.ajax({
type: "post",
url: "somepage.html",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Generate a unique token when you fire a request,
keep a list of valid tokens,
remove tokens when the request times out/fails,
check if token is still valid before executing success/error callbacks.
The same pattern can be adapted for a situation when you need to send frequent repeating requests (e.g. autocompletion/result filtering) and only the latest one's handler should fire.

How do I trigger the "error" callback in backbone.js collection.create?

collection.create(data, {
success:function(){ ... },
error: function(){ ... },
});
If I save it, and it hits the server, but the server validates an error, how do I let the client know? It seems that no matter what, "success" is called.
The error callback is triggered on a 4xx or 5xx HTTP response.
What are the HTTP response codes of your server errors?
The latest Backbone docs have a small blurb about this:
If a server-side validation fails, return a non-200 HTTP response code, along with an error response in text or JSON.
I think you need to make the server send a response code of not 200 ok.. like 500.
http://documentcloud.github.com/backbone/#Model-save

jquery error function help

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.

Categories