user982124
user982124

Reputation: 4610

jQuery AJAX - conditional success result based on data from PHP page

I have my first AJAX call with jQuery setup and working well. The final change I need to make is to check the result from the PHP page that is called for any database errors and display an error if required.

Here's my current Javascript with some comments where I would like to branch based on the result:

<script type="text/javascript">
    $(document).ready(function() {
        $("#storeManager").change(function(){
            var storeManager = $("#storeManager").val();
            $.post('editProject.php', { type: 'storeManager', storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {

                // if there was a database error from the editProject.php page it will be returned in this format:
                // Error: Database Error 456
                // If there is an "Error: " string in the result I would like to do the following
                $("#ajaxAlert").addClass("alert alert-danger");
                $("#ajaxAlert").html(data);


                // If there is no "Error: " string in the result I would like to do the following
                $("#storeManagerRow").addClass("success");
                $("#storeManagerRow").removeClass("danger");
                $("#ajaxAlert").hide();

            }).fail(function () {
                // no data available in this context
                $("#storeManagerRow").addClass("danger");
                $("#ajaxAlert").addClass("alert alert-danger");
                //append error to the div using its ID
                $("#ajaxAlert").html(data);

            });
         }); 
    }); 
</script>

I'm new to jQuery and AJAX and working things out as I go - just not sure how to branch based on the result (data) from the PHP page.

Upvotes: 1

Views: 589

Answers (1)

istos
istos

Reputation: 2662

Instead of returning html from your PHP script return a JSON object.

For a successful result you could return a data object like this:

{
  html: '<p>lorem ipsum</p>'
}

For a result with application errors you could have a data object like so:

{
  error: true,
  html: '<p>Error: Database Error 456</p>'
}

And in your callback simply check for the presence of the error property:

if (data.error) {
  $("#ajaxAlert").addClass("alert alert-danger").html(data.html);
  // ...
  return; // stop the execution of this function right here
}

Upvotes: 2

Related Questions