Reputation: 1408
I am trying to send a "notification" or error messages from php to ajax. I'm trying to achieve something like this:
php:
if (myString == '') {
// Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
// Send "stringEqualsFoo" error to ajax
}
ajax
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(){
alert("It works");
},
error: function() {
if(stringIsEmpty) {
alert("String is empty");
} else if(stringEqualsFoo) {
alert("String equals Foo");
}
}
});
How can I send error messages to ajax?
Update
Here's the php file I have. I tried using the echo
solution answers said, but when I output what the data
is (in ajax), I get undefined
:
<?php
$img=$_FILES['img'];
if($img['name']==''){
echo('noImage');
}else{
$filename = $img['tmp_name'];
$client_id="myId";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$pvars = array('image' => base64_encode($data));
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$out = curl_exec($curl);
curl_close ($curl);
$pms = json_decode($out,true);
$url=$pms['data']['link'];
if($url!=""){
echo "<h2>Uploaded Without Any Problem</h2>";
echo "<img src='$url'/>";
}else{
echo "<h2>There's a Problem</h2>";
echo $pms['data']['error'];
header("HTTP/1.1 404 Not Found");
}
}
?>
I added echo("noImage")
in if($img['name']==''){
Upvotes: 3
Views: 7559
Reputation: 3015
I've tried the bootstrap Model using jQuery AJAX And PHP with error handling
Javascript File:
// add receipt data
$('#insert_form').on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "includes/user-insert.inc.php",
method: "POST",
data: $('#insert_form').serialize(),
async: true,
beforeSend: function() {
$('#insert').val("Inserting");
},
success: function(data) {
$('#insert_form')[0].reset();
$('#add_reciept').modal('hide');
dataTable.ajax.reload(null, false);
if (data == "No") {
$('#alert-danger').addClass('alert alert-danger');
$('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
$('#alert-danger').fadeIn().show();
setTimeout(function() {
$('#alert-danger').fadeOut("slow");
}, 8000);
} else if (data == "Yes") {
$('#alert-success').html('<strong>Well done!</strong> A Record has been Added.');
$('#alert-success').addClass('alert alert-info');
$('#alert-success').fadeIn().show();
setTimeout(function() {
$('#alert-success').fadeOut("slow");
}, 8000);
}
},
error: function(err) {
$('#alert-danger').addClass('alert alert-danger');
$('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
$('#alert-danger').fadeIn().show();
setTimeout(function() {
$('#alert-danger').fadeOut("slow");
}, 8000);
},
complete: function(data) {
$('#insert').val("Insert");
}
});
});
process.inc.php file:
// check users again or not
$sql = "SELECT * FROM users_acc WHERE U_Email='$U_Email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo 'No';
} else {
$query = "
INSERT INTO users_acc(Firstname, Lastname, U_Email, U_Password, Gender, user_role_id)
VALUES('$Firstname', '$Lastname', '$U_Email', '$U_Password', '$Gender' , '$user_role_id')
";
echo 'Yes';
}
Upvotes: 0
Reputation: 18995
The thing is, if your php responds, then it's technically not a error, and must be handled in the success callback.
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(data){
alert('The response is: '+data);
if(data=="empty sting"){
alert("The string is empty");
} else if (data == 'foo') {
alert("The string equals 'foo'");
} else {
alert("It works");
}
},
});
And in your PHP:
if (myString == '') {
echo('empty string');
} else if (myString == 'foo') {
echo('foo');
}
Upvotes: 1
Reputation: 2702
The error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/
So if you return a response from your PHP server, the error function won't be triggered. However, you can define a function to handle the error based on the response you send from PHP:
success: function(data){
if (data === "stringIsEmpty") {
triggerError("stringIsEmpty");
} else if (data === "stringEqualsFoo") {
triggerError("stringEqualsFoo");
}
},
And then you can have the error function like this:
function triggerError(error) {
if (error === "stringIsEmpty") {
alert("Your string is empty!");
} else if (error === "stringEqualsFoo") {
alert("Your string is equal to Foo!");
}
}
If you make a request to let's say post.php, you can just return a string:
// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;
Or specifically for the example:
echo "stringIsEmpty";
For more information see: How to return data from PHP to a jQuery ajax call
Upvotes: 6
Reputation: 2098
You can trigger the jQuery error-handler by changing the http response code in php. Any 4xx or 5xx error should work, but best stay in rfc.
PHP:
// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";
jQuery:
[...]
error: function(jqxhr) {
alert(jqxhr.responseText)
}
[...]
Upvotes: 5
Reputation: 116
The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...
If you want to control some response of the server you can write this code in the "success" setting.
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response){
if (response == '') {
// Send "stringIsEmpty" error to ajax
} else if (response== 'foo') {
// Send "stringEqualsFoo" error to ajax
}
}
}
});
The PHP could be something like this
if (myString == '') {
echo '';
} else if (myString == 'foo') {
echo 'foo';
}
Upvotes: 0
Reputation: 718
So if your returned string is empty, or it equals "foo", you may think that is an error, but HTTP thinks it is a success, and you need to look for these strings in the "success" function.
Upvotes: -1