Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am attempting to send different error messages back to an HTML DIV depending on the PHP outcome. I have searched through here and other place but have been unable to locate an answer that seems to work for my situation... hopefully someone else can help me with this.

My HTML page includes a form that a user is asked to enter a reservation ID # (unique), once the user does this and presses "Search Reservation" a Jquery script is called to send the ID to a PHP script via AJAX. The Data is returned and then is populated into a form using a jquery plugin called, "populate".

Here is the script:

<script type="text/javascript">
$(document).ready(function(){
    resetForms('reservation');
    $('#form-reservation').submit(function(event){ 
        event.preventDefault();  //the page will no longer refresh on form submit.
    var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
        $.ajax({ 
            url: 'inc/searchres.php', 
            type: 'POST',
            data: 'resid='+resCheck, 
            success: function(data){  //data is all the info being returned from the php file 
                resetForms('reservation');  //clear forms
                $('#reservation-id').val(resCheck);  //add res ID back into text box
                var jsonData = $.parseJSON(data);  //parse returned JSON data so we can use it like data.name, data.whatever 
                $("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
                $('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
            },
            error: function(){
                $("#res-message").html('<a>There was an error with your request</a>');
            }
        });
    });
});
</script>

This was called from the following form (which also includes the DIV in which I would like to populate my error messages, res-message):

<form name="form_reservation" id="form-reservation">
                    <div style="padding:10px 20px 10px 10px;">
                    <label for="reservation-id">Reservation ID</label>
                        <input name="reservation_id" id="reservation-id" class="reservationid" style="width:120px !important"/>
                        <div class="res_message" id="res-message">&nbsp;</div>
                        <input type="submit" class="button" value="Search Reservation" style="width:150px !important; margin:10px 0px 0px 5px;"/>
                        <input type="button" class="button" value="Clear" style="width:150px !important; margin:10px 0px 0px 5px;" onclick="resetForms('reservation')" />
                    </div>
                </form>

The form that is populated should not be important for this question. Finally the PHP looks like such:

<?php
    include('config-searchres.php');

    $term = $_POST['resid'];
    $sql = mysql_query("SELECT * FROM ap_form_8 WHERE id = '$term'"); //select first name (element_1_1) from form #8
    //$sql = mysql_query("SELECT * FROM ap_form_8 WHERE element_12 = '$term'");  //real selector will look for unique number that has not been added to table yet

    if ($row = mysql_fetch_array($sql)){  //if reservation number exists
        if ($row['element_11'] != 'Cancelled'){  //if reservation has not already been cancelled
            if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){  //if reservation has not already passed date
                echo json_encode($row);
            }
            else  //Reservation already passed (old reservation)
            {
                echo $error = "Passed"; 
                //echo 'passed';
            }
        }
        else  //Reservation already cancelled
        {
            echo 'cancelled';
        }
    }
    else  //Reservation not found
    {
        echo 'not found';
    }
    mysql_close();
?>

I know next to nothing about PHP, but I do know that this script seems to work for populating my tables... just not displaying errors for other situations. 3 different errors, 'passed', 'cancelled', and 'not found' need to be passed back during their respective situations. Anyone have an idea?

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

The quick and dirty solution is to test the returned result to see if it is a string or an array. On your javascript:

                (...)
                var jsonData = $.parseJSON(data);  //parse returned JSON data so we can use it like data.name, data.whatever
                if (typeof(jsonData)=='object'&&(jsonData instanceof Array)) {
                    // jsonData is an array, populate success div
                    $("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
                    $('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});

                } else {
                    // jsonData is a simple string, so PHP returned an error. populate error div
                    $("#res-message").html('<a>There was an error with your request</a>');
                }
                (...)

Naturally, when handling the error, you can switch on jsonData contents to provide a specific error message if needed.

share|improve this answer
2  
The not so quick but cleaner solution would be to always return an array from PHP, with two elements: a success flag, and a payload. Then, the javascript-end would be a lot simpler (test the flag, use the specific payload on success/error based on the success flag) –  Sérgio Carvalho Apr 25 '12 at 2:32
add comment

It seems the issue is that the different error messages from the PHP code are not send as JSON string. So when using 'jsonData = $.parseJSON(data);' it gives and exception. May be you can try using the below code.

    <script type="text/javascript">
    $(document).ready(function(){
     resetForms('reservation');
     $('#form-reservation').submit(function(event){ 
     event.preventDefault();  //the page will no longer refresh on form submit.
     var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
     $.ajax({ 
        url: 'inc/searchres.php', 
        type: 'POST',
        data: 'resid='+resCheck, 
        success: function(data){  //data is all the info being returned from the php file 
            resetForms('reservation');  //clear forms
            $('#reservation-id').val(resCheck);  //add res ID back into text box
            try 
            {
             var jsonData = $.parseJSON(data);  //parse returned JSON data so we can use it like data.name, data.whatever 
             $("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
             $('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
            }
            catch 
            {
              $("#res-message").html('<a>There was an error with your request</a>');
              $('#json-reservation').populate({status:data});
            }
          }
        });
      });
     });
     </script>

I have not tested this code but atleast the logic should work.

share|improve this answer
 
I will give it a try, but how would I go about actually sending back the 3 different error messages: 'passed', 'cancelled', and 'not found'? Do I need to somehow save these to a variable in the PHP? –  tmparisi Apr 25 '12 at 12:42
 
In my code, if the output from the PHP is 'passed', 'cancelled' or 'not found', it shows the message 'There was an error with your request' and then populates the output. If you want to show different messages for 'passed', 'cancelled', and 'not found', then you can use an if condition and populate different messages. –  Harikrishnan Viswanathan Apr 25 '12 at 12:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.