从PHP发回不同的错误消息回到Ajax / Jquery脚本并填充HTML DIV ......?

时间:2012-04-25 02:12:51

标签: php jquery html ajax json

我正在尝试根据PHP结果将不同的错误消息发送回HTML DIV。我在这里和其他地方搜索过,但一直无法找到对我的情况有用的答案...希望其他人可以帮助我。

我的HTML页面包含一个表单,要求用户输入预订ID#(唯一),一旦用户执行此操作并按“搜索预订”,将调用Jquery脚本以通过AJAX将ID发送到PHP脚本。返回数据,然后使用名为“populate”的jquery插件填充到表单中。

这是脚本:

<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>

这是从以下形式调用的(其中还包括我希望填充我的错误消息的DIV,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>

填充的表单对于此问题不应该很重要。最后,PHP看起来像这样:

<?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();
?>

我对PHP几乎一无所知,但我知道这个脚本似乎适用于填充我的表...只是不显示其他情况的错误。在各自的情况下,需要传回3个不同的错误,“通过”,“取消”和“未找到”。有人有想法吗?

2 个答案:

答案 0 :(得分:0)

快速而肮脏的解决方案是测试返回的结果以查看它是字符串还是数组。在你的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>');
                }
                (...)

当然,在处理错误时,您可以打开jsonData内容以在需要时提供特定的错误消息。

答案 1 :(得分:0)

似乎问题是来自PHP代码的不同错误消息不会作为JSON字符串发送。所以当使用'jsonData = $ .parseJSON(data);'时它给出了例外。  也许您可以尝试使用以下代码。

    <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>

我没有测试过这段代码,但至少应该运行逻辑。