php script goes and retrieves certain records from mysql DB and returns JSON Object.
But back in the javascript i always get error in parsing json object.
i have tried various options with eval but nothing works.
Let me know if you find what i am doing wrong.
Thanks in advance
Response from PHP Script is -
Code: Select all
{"users":[{"id":"1","name":"john"},{"id":"2","name":"test"},{"id":"3","name":"anou"}]}-------------------------------------
Code: Select all
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - PHP example</title>
</head>
<script language="javascript" type="text/javascript">
var httpObject = null;
var my_JSON_object = {};
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput(){
if(httpObject.readyState == 4){
var myObject = eval( "(" + httpObject.responseText + ")" ); //THIS IS WHERE I get Syntax ERROR
//var myObject = JSON.parse('(' + httpObject.responseText + ')');
for (var i in myObject) {
alert(i + ': ' + myObject[i]);
}
}
}
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "http://localhost:7777/testjson.php", true);
httpObject.setRequestHeader("Content-Type", "application/json");
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
</script>
<body>
<form name="testForm">
Input text: <input type="text" onkeyup="javascript:doWork();" name="inputText" id="addDisplay" />
Output text: <input type="text" name="outputText" id="outputText" />
</form>
</body>
</html>PHP SCript
-----------------------------------------
Code: Select all
<?php
# Define MySQL Settings
define("MYSQL_HOST", "localhost");
define("MYSQL_USER", "xxxx");
define("MYSQL_PASS", "xxxx");
define("MYSQL_DB", "xxxx");
$conn = mysql_connect("".MYSQL_HOST."", "".MYSQL_USER."", "".MYSQL_PASS."") or die(mysql_error());
mysql_select_db("".MYSQL_DB."",$conn) or die(mysql_error());
$sql = "SELECT * FROM name";
$res = mysql_query($sql);
$arr = array();
while ($field = mysql_fetch_object($res))
{
$arr[] = $field;
}
echo '{"users":'.json_encode($arr).'}';
?>