user3446862
user3446862

Reputation: 15

Javascript function to change input fields

I'm trying to check if a user exists in my database and then change the values of my input fields to match that user's information. I have the following code but it doesn't seem to work.

    <button onclick="checkAvailability()">Check Availability</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function checkAvailability()
{
    $(function()
    {
        $.ajax(
        {
            type: 'POST',
            url: 'test.php',
            data: "name=" + $("#name").val(),
            dataType: 'json',
            success: function(row)
            {
                $('#name').val(row[0]);
                $('#address1').val(row[1]);
                $('#phone1').val(row[2]);
                alert('success');
            }
        });
    });
}
</script>

The alert goes off but none of the values are changed. I checked the response using Firebug and the response is a JSON object with the user's information. I'm not sure where the error is. Thank you for any input.

Upvotes: 0

Views: 51

Answers (2)

Ekansh Rastogi
Ekansh Rastogi

Reputation: 2546

In case you are getting a json then it might look like this

var json = [{"name": "sample"},{"phone":"sample"},{"address":"sample"}];

When you are doing row[0]. what you get is an object["name":"sample"] So you must make the following change

 success: function(row)
            {
                $('#name').val(row.name);
                $('#address1').val(row.address);
                $('#phone1').val(row.phone);
                alert('success');
            }

Also make sure you have input types with id's name, address1 and phone1

Upvotes: 0

chf
chf

Reputation: 763

If you have a json object you must use: $("#name").val(row.name);

Upvotes: 2

Related Questions