Javascript 使用Ajax将数据传递给PHP

Javascript 使用Ajax将数据传递给PHP,javascript,php,sql,ajax,Javascript,Php,Sql,Ajax,如何在不单击submit按钮的情况下将HTML中的输入文本数据传递给PHP函数 我已经有了使用Ajax从数据库获取数据的想法,但我只想查询特定的行。这里的想法是,只要在输入字段名称中输入名称,它就会自动查询数据库。如果该名称存在,则其他两个字段“地址”和“联系人”将自动填充 以下是我到目前为止的情况: <?php $server ="localhost"; $user ="root"; $password = ""; $db = "customers";

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

我已经有了使用Ajax从数据库获取数据的想法,但我只想查询特定的行。这里的想法是,只要在输入字段名称中输入名称,它就会自动查询数据库。如果该名称存在,则其他两个字段“地址”和“联系人”将自动填充

以下是我到目前为止的情况:

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

我能理解的是,当用户在文本框中键入或更改选择按钮时,应该发送数据

这在输入或选择标记onchange=funtcion\u name中非常简单,如下所示

功能myFun { var id=$input.val; $.ajax{ //在这里编写ajax代码 } }
看起来您并不是在按照手册尝试使用PHP或JavaScript。您应该遵循为使Ajax脚本正常工作而制定的示例/指南,并且您的MySQLi实现在几个关键方面也存在缺陷。您正在尝试创建一个类实例,但您使用的是MySQLi的过程版本,因此我认为应该会产生某种错误。然后,您将不绑定语句上的参数,从而为注入打开了大门。请注意,我使用PDO,因此您必须仔细检查MySQLi,我是根据手册指南执行的:

/fetch.php

表格页:


你需要发布一些代码。在这里发布代码,而不是图片。你犯了严重的拼写错误,这会导致错误,请修复这些错误,否则他们可能会认为这是正确的语法。OP没有提到jQuery,没有浪费对它的否决票,但它很差。@Rakeshkumarsharma它是$.ajax加上“a”而不是$.ajax加上“e”。此外,您不会将Ajax代码放在您指定的位置,而是填写预先确定的数据对象值,其中一些可能包含函数代码。如果我的答案或给出的其他答案解决了您的问题,请标记为正确,这样这个问题就不会被忽略。我只做了一些修改,但代码运行良好。谢谢:太好了,我想知道它是否有什么好处,尤其是MySQL的东西
<?php
# You should think about containing your connection inside a class or function
$server ="localhost";
$user ="root";
$password = "";
$db = "customers";
# This should be the class version of this library not the function
$con = new mysqli($server,$user,$password,$db);
# This part should work now
if($con->connect_errno){
    die(json_encode(['success'=>false,'msg'=>"cannot connect to the database".$con->connect_error]));
}
# I'm gonna switch to post here...
$input = (!empty($_POST['name']))? trim($_POST['name']) : false;
# If it's empty, just stop
if(empty($input))
    die(json_encode(['success'=>false,'msg'=>'Input is empty']));
# You have to bind parameters, this is a security hole
//$sql ="SELECT * FROM customers WHERE name = '$input'";
# Prepare the statement with a question mark as a placeholder
$query = $con->prepare("SELECT `name`,`contact` FROM customers WHERE name = ?");
# Put the value in here, indicating it is a string (s)
$query->bind_param('s',$input);
# Execute the query
$query->execute();
# Get the results from the query
$result = $query->get_result();
# Fetch the array as associative
$customer = $result->fetch_assoc();
# Add a success row in the array so the json parse is not malformed on return
$customer = (empty($customer))? ['success'=>false] : array_merge(['success'=>true],$customer);
# Print the string
die(json_encode($customer));
<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>