2

My form is returning data from PHP via jQuery. How can I create conditional statements based on the response in jQuery.

This is the jQuery:

  $.ajax({
                    type: "POST",
                    url: "createAlbum.php",
                    data: postData, 
                    success: function(data){
                        $('#message').fadeIn();
                        $('#message').html(data);
                    }
                  });

This is what it is returning from PHP:

if($error) {
        echo $error;
    }
    else {
        echo $success;
    }

So if the response is success, the message should hide after a few seconds, but if it is an error, it should wait till the user corrects it. Something like this:

success: function(data){
                    $('#message').fadeIn();
                    $('#message').html(data);

                    if (data.response == 'success') {
                        alert('Success');
                        setTimeout(function() {
                            $('#message').fadeOut();
                            }, 5000 );
                    } else if (data.response == 'error') {
                            alert('Error');
                       }
            }
4
  • What is happening? That looks pretty much right to me. Commented May 4, 2011 at 20:45
  • That isn't working for me. It is returning error alert even if the data is correct. Commented May 4, 2011 at 20:46
  • did you figure this out? which answer worked for you? Commented May 6, 2011 at 0:14
  • @AJ, your answer was greatly helpful but I went with the JSON approach. Commented May 6, 2011 at 11:08

3 Answers 3

3

Why don't you use the statusCode setting for your call to ajax() and have even more fine-grained control than just "success" and "error"? There are (or will be) many different ways your script could succeed or fail.

statusCode(added 1.5)Map Default: {}

A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({ statusCode: { 404: function() { alert('page not found'); } } });If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.


UPDATE:

I've added an example of how to use statusCode instead of success and error settings for ajax() call in Jquery. First, the test UI:

<html>
<head>
<title>jQuery Test Page</title>
<script type="text/javascript" src="jquery-1.6.js"></script>
<script type="text/javascript">
function displayMessage(message){
    $('#message').fadeIn();
    $('#message').html(message);
}

function successFunction(data){
    displayMessage(data);
}

function notFoundFunction(){
    displayMessage("Not Found!");
}

function errorFunction(){
    displayMessage("An Error Occurred!");
}

function invokeAjax(test){
    $.ajax({
        type: "POST",
        url: "test.php?test="+test,
        //data: postData,
        statusCode: {
            200: successFunction,
            404: notFoundFunction,
            500: errorFunction,
        }
    });
}
</script>
</head>

<body>
<h1 id="message" style="display:none;"></h1>
<a href="javascript:invokeAjax('success');">Invoke Ajax - Success (200)</a><br>
<a href="javascript:invokeAjax('notfound');">Invoke Ajax - Not Found (404)</a><br>
<a href="javascript:invokeAjax('error');">Invoke Ajax - Error (500)</a><br>
</body>
</html>

And here's the PHP script called by the Ajax:

<?php

$test = $_GET['test'];

if($test == 'success'){
    echo 'some meaningful data';
} else if($test == 'notfound') {
    http_send_status(404);
} else if($test == 'error'){
    http_send_status(500);
}
?>

I think it's pretty self-explanatory, but if you have any further questions, don't hesitate to ask.

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

1 Comment

Thanks for your response! How can I use statusCode in the above script?
0

Of course, to get AJ's solution to work, you need to respond from the server to the client with the correct headers - http://no.php.net/manual/en/function.header.php:

header('HTTP/1.1 404 Not Found');

or

header('HTTP/1.1 500 Internal Server Error');

Here is a list of HTTP codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Hope this helps :)

Comments

0

Thank you for your helpful answers. I solved it using JSON though!

PHP:

if($error) {

        echo json_encode(array('success' => false, 'text' => $error));
    }
    else {

        echo json_encode(array('success' => true, 'text' => $success));
    } 

jQuery:

if (data.success) {
            alert('Success');
            setTimeout(function() {
                $('#message').fadeOut();
            }, 5000 );
    } else {
        alert('Error ' + data.text);
    }

1 Comment

great job figuring it out. If you want to see a different way to do it, check out my updated answer.

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.