Having some trouble with AJAX/JQuery. Here is the context of my problem followed by a code sample:
What I am attempting to do is call a PHP script called getInfo.php and check whether or not some data is contained within a database. I can write queries easily enough but in terms of the code sample below how can I "tell" the success function to fail if it cannot find data in the database and run the error function instead?
$(document).ready(function(){
getInfo();
function getInfo(){
$.ajax({
type: "GET",
url: "getInfo.php",
data: "do=getInfo",
cache: false,
async: false,
success: function(result) {
$("#myInfo").remove();
alert("Data found");
},
error: function(result) {
alert("Data not found");
}
});
}
});
Any advice would be greatly appreciated. =)
A success callback that gets invoked upon successful completion of an Ajax request. A failure callback that gets invoked in case there is any error while making the request. A completion callback that gets invoked no matter a request completed with or without success.
What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
Step 2: Log fatal message in case of error or timeout $. ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) . done(function (data, textStatus, jqXHR) { // Process data, as received in data parameter }) . fail(function (jqXHR, textStatus, errorThrown) { // Request failed.
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });
The error handler is used to handle errors in your AJAX call.
You could echo 1
in your PHP script if the data was found and 0
if it was not found. Then you could use an if statement to determine what to do. For example:
success: function(result)
{
if(result == 1)
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
},
"success" gets called when the returned code is a "200" (successfull request). "error" gets called whenever another code is returned (e.g. 404, 500).
So I think you can do 2 things:
Let your getinfo.php return a boolean value (usually my approach)
{"success":true, ...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With