Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script:
include("db_connect.php");
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SET NAMES utf8");
$query = "SELECT * FROM models WHERE models.product_id='".$product_selected."'";
$result = mysql_query($query);
$json_object = "{ \"model\": [";
while($result_row = mysql_fetch_row($result)) {
$json_object .= " {\"model_name\" : \"".$result_row[1]."(".$result_row[2].")";
$json_object .= "\"},";
}
$json_object = substr($json_object,0,strlen($json_object)-1);
$json_object .= " ]};";
echo json_encode($json_object);
The resulting output of the PHP code above is a JSON-formatted response like this:
{ "model":
[
{"model_name" : "xxxxx "},
{"model_name" : "xxxxx "},
{"model_name" : "link2(U)"},
{"model_name" : "xxxxx)"}
]
};
However, upon receiving this response through Ajax, the following error occurs:
var my_JSON_object = {};
var xmlHttp = createXmlHttpRequestObject();
try {
xmlHttp.open("GET", "ajaxproduct_new.php?product_id=" product_id,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
my_JSON_object = JSON.parse( xmlHttp.responseText );
alert(my_JSON_object.model[0].model_name);
}
}
xmlHttp.send(null);
} catch (e){
alert("Can't connect to server:\" e.toString());
}
An attempt to trigger an alert for
my_JSON_object.model[0].model_name
results in the error message that my_JSON_object.model
is undefined.
If you have any insights on why this issue persists despite repeated attempts, please share your knowledge. Thank you!