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']==''){