Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send error messages from php to ajax

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

like image 327
Horay Avatar asked Jan 25 '26 10:01

Horay


2 Answers

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

like image 109
Timon Avatar answered Jan 28 '26 00:01

Timon


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)
}
[...]
like image 41
clemens321 Avatar answered Jan 28 '26 01:01

clemens321



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!