I want to pass an array from PHP file to JavaScript and store in JavaScript array. Here's the JavaScript code:
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
nameData = JSON.parse(xmlhttp.responseText);
console.log(xmlhttp.responseText);
}
}
xmlhttp.readyState=4;
xmlhttp.open("GET","mapPHPname.php?Zip="+zipcode,true);
xmlhttp.send();
PHP file:
<?php
$zip=isset($_GET['Zip']);
include 'dbconnect.php';
$sql="Select `name` from doctor where `zip` LIKE $zip";
$result = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($result);
array(name);
if($num_rows>=1)
{
$count=0;
while($res_array = mysql_fetch_assoc($result))
{
$name[$count]=$res_array['name'];
}
}
else
{
$name[0]="kashyap";
}
echo json_encode($name);
?>
I am getting this error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (< anonymous >)
1- You don't declare an array in this way: array(name)
Try instead: $name = array()
or $name = []
.
2- And quote your include include 'dbconnect.php';
3- Correct access to variable count
, at $name[count]=$res_array['name'];
, count
should be $count
.
And you're not actually looping it. You should make $count++
after saving to the $name
array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.