使用Ajax将数据传递给PHP

时间:2018-01-03 03:04:58

标签: javascript php sql ajax

如何在不单击提交按钮的情况下将HTML中的输入文本数据传递给PHP函数?

我已经有了使用Ajax从数据库中获取数据的想法,但我只想查询特定的行。这里的想法是,只要在输入字段name上输入名称,它就会自动查询数据库。如果存在所述名称,则会自动填充其他两个字段addresscontact

这是我到目前为止所做的:

<?php
    $server ="localhost";
    $user ="root";
    $password = "";
    $db = "customers";

    $con= new mysqli_connect($server,$user,$password,$db);

    if($con->connect_errno){
        die("cannot connect to the database".$con->connect_error);
    }

    $input = $_GET['name'];
    $sql ="SELECT * FROM customers WHERE name = '$input'";
    $result= $con->query($sql);
    $customer= mysqli_fetch($result, MYSQLI_ASSOC);
    echo json_encode($customer);
?>

<body>
<script> 
document.getElementById('name').addEventListener('change',thereExist);

function thereExist()
{
    var searchCustomer = new XMLHttpRequest();
    // here should call the php  function and pass the data from 
    input text 'name'
}

function getData()
{
    var xhr = new XMLHttpRequest();
    xhr.open('GET','fetch.php',true);
    xhr.onload = function(){
        if(this.status == 200){
            var customer =JSON.parse(this.responseText);
            var output='';
            document.getElementById('address').value(customer.name);
            document.getElementById('contact').value(customer.contact);
        }
    }
}
</script>

<form action="" method="GET">
    Name: <input type="text" id="name" name="name" value="" />
    Address: <input type="text" id="address" name ="address" value="" />
    Contact: <input type="text" id="contact" name="contact" value="" />
</form>    
</body>

2 个答案:

答案 0 :(得分:0)

您似乎没有关注尝试PHP或JavaScript的手册。您应该遵循规定的示例/指南,以使Ajax脚本正常工作,并且您的MySQLi实现在几个关键方面也存在缺陷。您正在尝试创建一个类实例但是您正在使用MySQLi的过程版本,所以我想应该会产生某种错误。然后你不会在声明上绑定参数,从而打开你自己的注射。一个注意事项,我使用PDO,所以你必须仔细检查MySQLi,我是根据手册指南做的:

<强> /fetch.php

<body>
<script> 
// Create a simple ajax function
function aPoster(dataObj)
    {
        var xhr = new XMLHttpRequest();
        // Open via post
        xhr.open('POST',dataObj.sendto,true);
        // Send the header
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // Set the success response 
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                dataObj.success(this.responseText);
            }
        };
        // Send the request
        xhr.send(dataObj.values);
    };
// Shorthand to get obj by id (optional function)
function getId(elem)
{
    return document.getElementById(elem);
}
// Set the event listener
getId('name').addEventListener('change',function(){
    // Use our ajax function
    aPoster({
        // Set where to post to
        'sendto' : 'fetch.php',
        // Send the query string with value from field
        'values' : "name="+getId('name').value,
        // Set the success function for the return
        'success' : function(response){
            // I like to set a try here incase the parse fails
            try {
                // Parse
                response    =   JSON.parse(response);
                // Check if there was a successful return
                if(response.success == true) {
                    // .value is not a method, you have to assign here
                    getId('address').value = response.name;
                    getId('contact').value = response.contact;
                }
            }
            catch(Exception) {
                console.log('Return error: '+Exception.message);
            }
        }
    });
});
</script>
<form action="#" method="POST">
    Name: <input type="text" id="name" name="name" value="" />
    Address: <input type="text" id="address" name ="address" value=""/>
    Contact: <input type="text" id="contact" name="contact" value=""/>
</form>
</body>

表单页

{{1}}

答案 1 :(得分:-2)

我可以理解,当用户输入文本框或更改选择按钮

时,应该发送数据

这在输入或选择标签onchange =(“funtcion_name()”)中非常简单,如下所示

<html>
  <body>
    <input type="text" id="input" onchange = "myFun()">
    <script>
       function myFun()
       {
          var id = $("#input").val();
          $.ajax({
              
              //write your ajax code here
          
          })
       }
    </script>
  </body>
</html>