3

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

2
  • Copy and paste the code and make the appropriate changes. Your question is unclear. Commented Nov 11, 2015 at 18:51
  • I finally got why it was giving weird results. Is there a way of doing what your answer said without outputing anything to the website? Meaning, without showing "stringIsEmpty" on the actual website? Commented Nov 11, 2015 at 23:15

6 Answers 6

6

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

Sign up to request clarification or add additional context in comments.

9 Comments

Edited the answer to be a bit more clear, if you return "stringIsEmpty" from your PHP code, you can handle that on the AJAX side like that.
How can I return "stringIsEmpty" from the php code?
Adjusted again with some examples. For more information see: stackoverflow.com/questions/2410773/…
I tried what you said, and it displays on the website "foo", but it doesn't call the "alert". I don't want it to display in the website, I just want to do something in ajax, aka an alert.)
You can try removing processData: false from your $.ajax call, this makes sure the data returned is returned as a query string. Otherwise I would not know either, I don't know how your entire code structure looks (aka your php and js files)
|
5

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)
}
[...]

1 Comment

This is what I was looking for, the HTTP status codes list might help others.
1

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');
}

11 Comments

Thanks! I tried what you said, and it displays on the website "foo", but it doesn't call the "alert". I don't want it to display in the website, I just want to do something in ajax, aka an alert.)
@Horay try the edit. If doesn't work, please tell me what does the first alert say.
It says: "The response is: undefined"
@Horay oh my. Edited again.
At the first alert, the variable is response. Did you mean data?
|
0

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';
}

1 Comment

Thanks! I tried what you said, and it displays on the website "foo", but it doesn't call the "alert". I don't want it to display in the website, I just want to do something in ajax, aka an alert.)
0

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';
}

Comments

-1

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.

2 Comments

The first answer was not complete, and I didn't see the second two until I had finished writing mine.
The first is more complete than yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.