dongxu2398 2012-04-22 15:45
浏览 78
已采纳

使用1个HTML表单:询问用户唯一标识符,从数据库获取记录,解析为JSON,使用jquery populate插件填充HTML页面表单?

Let me start by saying that I am not an expert in any one type of code, instead, however, I tend to be okay at piecing things together and making it work! My latest issue is perhaps a little too technical for my know how. Here is what I am trying to accomplish:

I am using an HTML page with a form to grab a unique identifier from the user. Then PHP (to grab database information) and JSON (to parse that information into a format for use in HTML). Finally I am using the jquery plugin “Populate” to send this information into the desired form fields on the HTML page (a separate form from the one getting the unique identifier).

I have a HTML page with 2 forms on it. The first form:

    <form name="form_reservation" id="form-reservation">
        <div style="padding:10px 20px 10px 10px;">
            <label for="reservation-id">Reservation ID</label>
                <input name="reservationid" class="reservationid" style="width:120px !important"/>
                    <div class="json-sample" id="json-simple-sample">&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 Javascript to grab this submit is now:

<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', //default is GET, you are using POST(*SEE: [1]) 
            data: 'resid='+resCheck, 
            success: function(data){  //data is all the info being returned from the php file 
                var jsonData = $.parseJSON(data);  //parse returned JSON data so we can use it like data.name, data.whatever 
                $('#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']});
            }
        });
    });
});
</script>

The purpose of the previous form is to ask the user for a unique identifier. Once the user clicks “Search Reservation” this unique identifier is used to search a database to see if it exists… This is an external php file called searchres.php (thought I realize this php file is not properly linked to the form, as I couldnt figure out how to do it so the page would not reload or change links):

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

$term = $_POST['resid'];
$sql = mysql_query("SELECT * FROM ap_form_8 WHERE element_1_1 = '$term'"); //select first name (element_1_1) from form #8

if ($row = mysql_fetch_array($sql)){  //if reservation number exists
    if ($row['element_10'] != '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 'passed';
        }
    }
    else  //Reservation already cancelled
    {
        echo 'cancelled';
    }
}
else  //Reservation not found
{
    echo 'not found';
}
mysql_close();
?>

So to this point, the user has entered their unique number and the php file has searched the database for it. We have also converted our sql query into JSON format. I now need to populate the other form from the HTML page with the data that it has received. The other form looks like (sorry this is a big one):

   <form name="json_reservation" id="json-reservation" action="results.php" method="post" target="_blank" style="margin-top:15px">
                <fieldset>
                    <legend>Personal Information</legend>
                    <ul class="controls">
                        <li>
                            <label for="first-name">First Name</label>
                            <input name="personal_first_name" id="personal-first-name" type="text" class="text" maxlength="" value="" disabled readonly/>
                        </li>

                        <li>
                            <label for="last-name">Last Name</label>
                            <input name="personal_last_name" id="personal-last-name" type="text" class="text" maxlength="" value="" disabled readonly/>
                        </li>

                        <li>
                            <label for="personal[country]">Phone</label>
                            <input name="personal_phone_1" id="personal-phone-1" type="text" class="text" style="width:110px !important" maxlength="" disabled readonly/>
                        </li>
                        <li>
                            <label for="email">Email</label>
                            <input name="personal_email" id="personal-email" type="text" class="text" maxlength="" value="" disabled readonly/>
                        </li>
                    </ul>
                </fieldset>

                <fieldset>
                    <legend>Reservation Information</legend>
                    <ul class="controls">

                        <li>
                            <label for="status">Reservation Status</label>
                            <input name="reservation_status" id="reservation-status" type="text" class="text" style="width:110px !important" maxlength="" value=""  disabled readonly/>

                        </li>

                        <li>
                            <label for="date">Date</label>
                            <input name="reservation_date" id="reservation-date" type="text" class="text" style="width:110px !important" maxlength="" value="" disabled readonly/>
                        </li>

                        <li>
                            <label for="time">Time</label>
                            <input name="reservation_time" id="reservation-time" type="text" class="text" style="width:110px !important" maxlength="" value=""  disabled readonly/>
                        </li>

                        <li>
                            <label for="party">Number in Party</label>
                            <input name="reservation_party" id="reservation-party" type="text" class="text" style="width:110px !important" maxlength="" value=""  disabled readonly/>

                        </li>

                        <li>
                            <label for="specialrequest">Requests</label>
                            <textarea name="reservation_special_request" id="reservation-special-request" rows="3" wrap="virtual" class="specialrequest" style="width:60% !important" disabled readonly/></textarea>
                        </li>

                        <li>
                            <label for="coupon">Using Coupon/Promotion</label>
                            <input name="reservation_using_coupon" id="reservation-using-coupon" type="text" class="text" style="width:110px !important" value="" disabled readonly/> # <input name="reservation_coupon_code" id="reservation-coupon-code" type="text" class="text" style="width:110px !important" maxlength="" value=""  disabled readonly/>
                        </li>

                    </ul>
                </fieldset>
            </form>

So anyhow, this is where I am at, and at this point I know there are A LOT of issues with not only my code, but my method. Because of that, any tips would be greatly appreciated as I have searched high and low at this point.

Another point to mention, is that I really wanted both of these forms to interact nicely on one HTML page, without reloading it. External Link can be found: http://goo.gl/IFVv4 Don't worry about "part 3" of the form on the external link, as that is something I will mess with at a later date.

UPDATE: I have edited the code above to show where it is I am at now. Your help was excellent and got me quite far but now I think my problem resides in the php file... thoughts?

  • 写回答

1条回答 默认 最新

  • douchuopiao9002 2012-04-22 17:35
    关注

    One of the main things I saw here is that you don't understand the process of stopping a form submit, performing a request in the background, and then handling the data that is returned, so I'm going to outline this for you as simply as possible and hopefully it will help.

    First, we need to capture the form submit, in jQuery, we can do it like this ->

    $('#json-hierarchal').submit(function(){});
    

    Now that we know how to capture the submit of the form, we need to figure out how to stop the default behavior from submitting and reloading the page, we do this by accessing the event argument, and applying the function preventDefault();. (For your sake

    $('#json-hierarchal').submit(function(event){
      event.preventDefault(); // the page will no longer refresh on form submit.
    });
    

    Now that we've stopped the default submit, we can use $.ajax to send the data over to the php file so that it can parse it, and output what we need depending on what we sent.

    $('#json-hierarchal').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: 'searchres.php',
        type: 'POST', //default is GET, you are using POST(*SEE: [1])
        data: 'resid='+resCheck,
        success: function(data){//data is all the info being returned from the php file
          var jsonData = $.parseJSON(data);//parse returned JSON data so we can use it like data.name, data.whatever
          //I don't know how $.populate works, so I'm assuming we find each item returned in the json array, iterate over each occurence, and run populate on it?     
          $.each(jsonData, function(index,value){
            $('#form-hierarchal').populate(value);
          });
        }
      });
    });
    

    References

    [1] - GET/POST are interchagned based on REST and SOAP practices. When we need to get data from the server we use the GET method (We expect data to be returned to the server from the database, or an external file). When we need to post data to the server so that it can be A) Inserted into a Database or B) written to a file (simplicities sake here) we use the POST method. It's very important to learn to follow these practices as often as possible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值