My goal is to Prompt the user for a Location, and call my php program which will get that location's record from the database. Then send the JSON object back to the calling Javascript function which will then populate the user Form with the data from the database record.
I am stuck with figuring out the proper format to create the JSON and once received by the Javascript function, how to parse it properly to populate the user form.
Here is my Javascript function that should prompt the user, and call the php to retrieve the record from the database.
function partModify() {
var WPN = prompt("Please enter the West Part Number", "Harry Potter");
if (WPN != null) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// document.getElementById("txtHint").innerHTML = this.responseText;
var frm = document.getElementById("form-ajax");
var i;
// console.dir(response); // for debug
alert(this.responseText);
for (i in this.responseText) {
if (i in frm.elements) {
frm.elements[i].value = this.responseText[i];
}
}
}
}
xmlhttp.open("GET","part_get.php?q=" + WPN,true);
xmlhttp.send();
}
}
Here is the PHP program that gets the database record and sends it back via JSON.
<?php
$q = ($_GET['q']);
// Build the query based on the passed in parameters
if(!empty($q)) {
//The query
$query = "SELECT * FROM part_data WHERE WestPartNumber = '$q'";
//echo ($query); //see how our query look like at the moment
$username="xxxx";
$password="xxxx";
$database="xxxx";
$datahost="xxxx";
mysql_connect($datahost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$result=mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$temp[] = $row;
}
echo json_encode($temp);
mysql_close();
exit;
} else {
echo 'Empty call';
}
echo 'Exiting Call';
?>
The closest I have been able to get is that when I display the JSON object in my Javascript using the alert() call, i get the whole PHP file text along with the database record at the end.
Can someone help educate me on what I am doing wrong?
Rich