views:

46

answers:

2

Hi i want to load data from mysql database to php page using jquery and json. When user choose the name from select box, it load the person data into the text field.

this is my html code (select)

<select name='name' id='name'>
<option value='1'>John</option>
<option value='2'>Marco</option>    
<option value='3'>Charles</option>    
</select>

text field that i want to populate with the person data

<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>

getpersonData.php

<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);

echo json_encode($data);
?>

the ajax call

$.ajax({
type: "POST",
async : false,
url: 'http://test.com/getpersonData.php',
dataType: 'json',
data : {
    id : $("#id").val(),
},
success : function(data) {
    //what to insert here?

},
error : function(XMLHttpRequest, textStatus, errorThrown) {
    alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
}
}); 

What code should i use at the success function? Thanks

+1  A: 

I'm guessing your DB column names here, but maybe something like this

$('#firstname').val(data.firstname);
$('#phonenum').val(data.phonenum);
Phil Brown
Thank you. Going to test now! :D
cyberfly
Don't forget to set the content-type header as Calvin pointed out
Phil Brown
+3  A: 

First, you should set your Content-type header right before you echo your json_encode in getpersonData.php:

header("Content-type: application/json");
echo json_encode($data);

In your success function you would do something like:

$("#firstname").val(data.firstname); //firstname is the key of the user's firstname from your mysql query
Calvin L
Thank you for the help :)
cyberfly