1

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.

3
  • You have a syntax error in your ajax code. Commented Apr 1, 2014 at 19:15
  • @RenéRoth jsfiddle doesn't work with PHP as far as I know? Commented Apr 1, 2014 at 19:20
  • @Musa mind expanding on that? Commented Apr 1, 2014 at 19:21

3 Answers 3

3

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.";
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for replying. This code looks like it should do everything that I need it to but I've been pulling my hair out trying to get it to work. I know that my libraries are loading OK since I am also using a jQuery plugin for automatically filling in state and city based on the user's zip code. I've tested PHP on my IIS server multiple times. May I ask what other settings you have besides the code? If it's working OK for you (put in 0123456789 in the first textbox, get data automatically in the other two) then I don't know what could be wrong since I'm using your code. So confused.
try to enable the developer tools(by pressing the F12 key) and check whether there are any errors you've while running the program
Thanks for the suggestion. It lead me to fix the issue. See my edit if you want to see how.
2

Your data input in the ajax call should be:

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

5 Comments

Thank you for the suggestion. I changed it, but autocomplete still isn't working unfortunately.
added exit(); still no luck.
You know what you are assigning the numbox value to the $num. Add == to your comparison in the php. This should work this time.
I added it and now when I access the .php file it prompts "Bad input" from my else instead of JSON data like it did with a single operator. Autofill still didn't work though :(
Remove the if else condition to verify the important part of your code - that is to autofill the firstname and lastname. once you are able to auto fill then add back your if condition and check if your if condition is checking the values correctly and whether you are actually passing 0123456789 through the input box.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.