I'm trying to make a PHP file retrieve data from a SQL DB with an Ajax call, and store data in JSON format.
Ajax call
$.ajax({
method:"POST",
dataType:"json",
crossDomain:true,
url:"getCourses.php",
success: function(response){
var courses=JSON.parse(response);
var el="";
for(var i=0;i<courses.length;i++)
{
console.log(courses[i].title);
}
},
error: function(request,error){
console.log("ERROR: Request " + request + "\nSpecific Error: " + error);
}
});
PHP function
//this is a test, not the actual SQL query
$query="SELECT * FROM courses ORDER BY id;";
$result=$mysqli->query($query);
if($result->num_rows >0) //if there is at least one row...
{
$myArray= array(); //...create an array...
while($row = $result->fetch_array(MYSQL_ASSOC)){ //...fetch it...
$myArray[]=$row; //...and add its row to $myArray ([] means autoincrement).
}
echo json_encode($myArray);
However, the Chrome console just gives me a parserror. I've been bashing my head since yesterday, and I can't seem to find the problem. I know that JSON has trouble with non-UTF8 strings, but even doing a utf8_encode just gives this error.
UPDATED
I've only removed the JSON.parse method as told, and substituted it with
var courses=response;
In the PHP file instead, I've added the headers and this
foreach ($myArray as $row)
{
//UTF8 encoding to avoid parsing problems
htmlentities($row['title'],ENT_QUOTES | ENT_IGNORE, "UTF-8");
htmlentities($row['description'],ENT_QUOTES | ENT_IGNORE, "UTF-8");
}
before the JSON encode. The Chrome console always returns me this
ERROR: Request [object Object]
Specific Error: parsererror