Autocompleting textboxes from JSON data in a PHP f

2019-08-05 09:53发布

问题:

I have a bit of a quirky problem. I need to make sure that textboxes in my form get autofilled with 2 JSON objects created in a PHP script based on user input from another textbox in the form.

HTML:

<p>Number: <input type="text" name="numbox" id="numbox" maxlength="10"></p>
<p>First Name: <input type="text" id="firstnamebox" maxlength="20" name="firstnamebox"></p>
<p>Last Name: <input type="text" id="lastnamebox" maxlength="20" name="lastnamebox"></p>

jQuery:

$(document).ready(function () {
$("#numbox").keyup(function () {
    var el = $(this);

    if (el.val().length === 10) {
        $.ajax({
            url: "http://localhost/test.php",
            dataType: "json",
            type: "POST",
            data: {el.val()},
            success: function (result) {
                $("#firstnamebox").val(result.firstname);
                $("#lastnamebox").val(result.lastname);
            }
        });
    }
});
});

test.php

<?php

$num=$_POST["numbox"];

if ($num="0123456789")
{
    $fill = array('firstname' => "John", 'lastname' => "Smith",);
    echo json_encode($fill);
}
else
{
    echo "Bad input.";
}

?>

The JSON string works on my server, so I don't think that my PHP is bad. The logic is supposed to be where as soon as the user types in 0123456789 into the first textbox, the other 2 get populated with John and Smith respectively. The autocomplete is not working at all (probably due to my jQuery/AJAX code), so I would appreciate any help that you can give me in regards to solving this problem.

EDIT: I figured out through the error console that my jQuery couldn't connect to my localhost. I fixed this by allowing cross-origin communication. Had to add

header("Access-Control-Allow-Origin: *");

to the top of my PHP script to allow the connection. It can also be changed from your server control panel. Next issue was due to my jQuery code. A much more experienced developer suggested some code changes and now it looks like this:

$(function () {
$("#numbox").keyup(function () {
var el = $(this);

    if (el.val().length === 10) {
        $.ajax({
            url: "http://localhost/test.php",
            dataType: "json",
            type: "POST",
            data: "numbox="+el.val(),
            success: function (result, success) {
                $("#firstnamebox").val(result.firstname);
                $("#lastnamebox").val(result.lastname);
            }
        });
    }
});
});

I'm just glad it works. Thanks to anyone that assisted me with this.

回答1:

try this, this is working fine,i've tested this in my system.

$(function () {
$("#numbox").keyup(function () {
    var el = $(this);

   if (el.val().length === 10) {

        $.ajax({
            url: "test.php",
            dataType: "json",
            type: "POST",
            data: {'numbox':el.val()},
            success: function (result) {

                //try to put alert(result); to see what response you've got

                response = jQuery.parseJSON(result);
                $("#firstnamebox").val(response.firstname);
                $("#lastnamebox").val(response.lastname);
            }
            error: function(error) {
            alert(error);
            }
            });
        }
    });
});

in test.php

$num=(!empty($_POST["numbox"]))?$_POST["numbox"]:die('NUM is empty');

if ($num=="0123456789")//double equal to
{
    $fill = array('firstname' => "John", 'lastname' => "Smith",);
    echo json_encode($fill);
}
else
{
    echo "Bad input.";
}


回答2:

Your data input in the ajax call should be:

data: {'numbox':el.val()}


回答3:

Try using either $.getJSON() instead of $.ajax() or doing $.parseJSON(result) before trying to access it.