I want to load data from a MySQL database 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?
$_POST['id']intoselect * from person where ID='$id'. This leaves your code open to SQL injection. Switch from the outdated mysql driver to PDO and prepared statements.SELECT *here. The result row should be fetched as an associative array rather than combined associative and numeric array. Doing both will just result in a longer response message.mysql_fetch_array($result, MYSQL_ASSOC)or justmysql_fetch_assoc($result)SELECT *and combined arrays are supposed to be separate things, but I can no longer edit the comment to clarify this.