How to load data using jQuery and JSON?
I want to load data from a MySQL dat开发者_Go百科abase to a PHP page using jQuery and JSON. When the user choose the name from the select box, it loads the person's 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>
The 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 for the success
function?
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
I'm guessing your DB column names here, but maybe something like this
$('#firstname').val(data.firstname);
$('#phonenum').val(data.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);
header("Content-type: application/json");
echo json_encode($data); ?>
main file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Load JSON data through jQuery and PHP </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
load_data($('#name').val());
$('#name').change(function(){
load_data($('#name').val());
});
});
function load_data(personid)
{
$.getJSON("getpersonData.php", {id: personid}, function(data){
$('#firstname').val(data['firstname']);
$('#phonenum').val(data['phonenum']);
});
}
</script>
</head>
<body>
<select name="name" id="name">
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
</body>
</html>
精彩评论