Jquery的/AJAX下拉选择时填充的HTML形式 [英] Jquery/AJAX populated HTML form when dropdown selected

查看:73
本文介绍了Jquery的/AJAX下拉选择时填充的HTML形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在页面上填充表格.使用下拉选项的ID作为SQL语句中的ID,从MySQL数据库中提取填充表单所需的信息.我当时以为我可以将信息存储在$ _SESSION ['formBookings']中,并在刷新后填充表单(这已经发生了,因为我在提交后使用会话变量填充表单.

I am trying to populate a form on my page. The information required to populate the form is pulled from a MySQL database using the ID of the drop down option as the ID in the SQL statement. I was thinking that I can store the information in $_SESSION['formBookings'] and on a refresh this will populate the form (this is already happening as I am using the session variable to populate the form after a submit.

我无法在表单上附加一个提交按钮,因为我已经有一个提交按钮,而老板不希望有另一个按钮.我希望表单最终在选择一个选项时自动刷新页面.如果SQL语句中的数据已存储在会话数组中,则将填充该表单.

I can not have a submit button attached to the form as I already have one and the boss doesn't want another. I would like the form to eventually automatically refresh the page on the selection of an option. If the data from the SQL statement has been stored in the session array then the form will be populated.

这是我到目前为止所拥有的:

Here is what I have so far:

JQuery:

<script>
$(document).ready(function(){
    $('select[name=recall]').on('change', function() {var recall = $(this).val() 
    //$(function () 
      //{
        //-----------------------------------------------------------------------
        // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
        //-----------------------------------------------------------------------
        $.ajax({                                      
          url: 'recall.php',                  //the script to call to get data          
          data: "recall: recall",             //you can insert url argumnets here to pass to api.php
                                           //for example "id=5&parent=6"
          dataType: 'json',                //data format      
          success: function(data)          //on recieve of reply
          {
            var id = data[0];              //get id
            var vname = data[1];           //get name
            //--------------------------------------------------------------------
            // 3) Update html content
            //--------------------------------------------------------------------
            $('div#box1').load('DFBristol.html');//html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
            //recommend reading up on jquery selectors they are awesome 
            // http://api.jquery.com/category/selectors/
          //} 
          });
        });
      });
    });
</script>

HTML:

<select name='recall' id='recall'>
                    <option selected></option>
                        <?php
                            session_start();
                            $user = 'root';
                            $pass = '';

                            $DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
                            $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                            $DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

                            $recall = $DBH->prepare('SELECT * FROM bookings WHERE dateInputted >= now() - INTERVAL 2 DAY');
                            $recall->execute();
                            $recallResult = $recall->fetchALL(PDO::FETCH_ASSOC);

                            foreach ($recallResult as $key) {
                                echo '<option id='.$key["ID"].'>'.$key['ID'].' - '.$key['branch'].' - '.$key['title'].' '.$key['firstName'].' '.$key['lastName'].'</option>';
                            }
                        ?>
                    </select><br />

SQL文件(recall.php):

The SQL file (recall.php):

<?php
$user = 'root';
$pass = '';

$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);

echo json_encode($recallFormResult);

?>

我试图使用data参数将jquery中的变量'recall'传递到SQL语句中,但没有任何反应.

I have tried to pass the variable 'recall' from the jquery into the SQL statement using the data argument but nothing happens.

有人可以帮助我理解我做错了什么以及如何解决.

Could someone please help me understand what I am doing wrong and how I can resolve it.

推荐答案

到目前为止,您发布的代码似乎有两个问题:

On a quick glance there seems to be two issues with the code you've posted so far:

即使$.ajax() 默认情况下默认为GET请求类型,也很好指定它.您的请求中还存在语法错误-您已使用});关闭了success回调,其中该回调应仅是}:

Even though $.ajax() defaults to a request type of GET by default, it's good to specify it. There is also a syntax error in your request — you have closed the success callback with a }); where it should be a } only:

$.ajax({                                      
    url: "recall.php",
    data: {
        recall: recall
    },
    type: "GET",               // Declare type of request (we use GET, the default)
    dataType: "json",
    success: function(data)
    {
        var id = data[0];
        var vname = data[1];
        $('div#box1').load('DFBristol.html');
    }                         // The problematic closure
});

甚至更好:代替使用不推荐使用的jqXHR.success()函数,而使用.done() promise对象,即:

Even better: instead of using the deprecated jqXHR.success() function, use the .done() promise object instead, i.e.:

$.ajax({                                      
    url: "recall.php",
    data: {
        recall: recall
    },
    type: "GET",               // Declare type of request (we use GET, the default)
    dataType: "json"
}).done(function() {
    // Success
    var id = data[0],
        vname = data[1];
    $('div#box1').load('DFBristol.html');
});

修复文件recall.php

当您向recall.php发出AJAX GET请求时,文件需要知道您打算传递哪些变量(尚未定义).您可以使用$_GET[](请参阅文档)进行操作,即:

Fixing the file recall.php

When you make an AJAX GET request to recall.php, the file needs to know what variables you intend to pass, which you have not defined. You can do that using $_GET[] (see doc), i.e.:

<?php
// Assign the variable $recall with the value of the recall query string from AJAX get request
// I recommend doing a check to see if $_GET['recall'] is defined, e.g.
// if($_GET['recall']) { $recall = $_GET['recall']; }
$recall = $_GET['recall'];

// The rest of your script, unmodified
$user = 'root';
$pass = '';

$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);

echo json_encode($recallFormResult);
?>

注意:但是,如果您选择发出POST请求,则应使用$_POST[](

Note: However, if you choose to make a POST request, then you should use $_POST[] (see doc) instead :)

这篇关于Jquery的/AJAX下拉选择时填充的HTML形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆