tctc91
tctc91

Reputation: 1363

jQuery ajax success conditional..?

I'm running the following php script through AJAX and need to integrate some error management into it:

$exists = file_exists('../temp/' . $email . '/index.html');
if($exists) {
    echo "ERROR!!!";
} else {
    createUserDirectory($email);
}

In the AJAX success function, how can I determine whether the script ran successfully or produced an error?

If it returns OK, I want to perform the redirect as it is at the moment, but if there's an error, I want to instead add the error to a DIV within the document (and not redirect of course...).

    $.ajax({
           type: "POST",
           url: 'generate/build.php',
           data: $("#generateStart").serialize(), // serializes the form's elements.
           success: function(data)
           {
              window.location.href="generate-site.php?user=" + data.replace(/^ +/,"") + ""; // Redirect to publish.php and remove any spaces from the URL (bug fix).
           }
         });

Thanks.

Upvotes: 2

Views: 361

Answers (3)

wsanville
wsanville

Reputation: 37516

Your PHP script should return a 4xx or 5xx HTTP status code to indicate failure. Then, the error method of jQuery's ajax object will be called.

Upvotes: 4

Dave
Dave

Reputation: 2417

You probably want to add two parts to this: an error callback on the $.ajax function to see if the request failed on the net and then a check on the return value to see if it failed server validation (if a file exists in this case).

Example:

$.ajax({
    ...
    success : function(data) {
         if(data && data != "ERROR!!!") {
             //redirect
         }
    },
    error: function(jqXHR, textStatus, errorThrown) {
         //Log error, display feedback to user, etc...
    }
);

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

Inside your success handler, check if(data == 'ERROR!!!').

Upvotes: 0

Related Questions