ajax - JSON parsing an array from PHP filled with SQL data returns [object Object] -


i'm trying make php file retrieve data sql db ajax call, , 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 test, not actual sql query $query="select * courses order id;"; $result=$mysqli->query($query);  if($result->num_rows >0) //if there @ least 1 row... {     $myarray= array(); //...create array...     while($row = $result->fetch_array(mysql_assoc)){ //...fetch it...          $myarray[]=$row; //...and add row $myarray ([] means autoincrement).     }       echo json_encode($myarray);  

however, chrome console gives me parserror. i've been bashing head since yesterday, , can't seem find problem. know json has trouble non-utf8 strings, doing utf8_encode gives error.

updated

i've removed json.parse method told, , substituted with

var courses=response; 

in php file instead, i've added headers , this

foreach ($myarray $row)     {         //utf8 encoding avoid parsing problems         htmlentities($row['title'],ent_quotes | ent_ignore, "utf-8");          htmlentities($row['description'],ent_quotes | ent_ignore, "utf-8");      } 

before json encode. chrome console returns me this

error: request [object object] specific error: parsererror 

you should not parse json manually:

var courses=json.parse(response); 

as have specified datatype json, jquery parse already, response object.

so need:

success: function(courses){     var el="";     for(var i=0;i<courses.length;i++)     {         console.log(courses[i].title);     }  }, 

note need output valid json when specify datatype that, if if condition in php script not met, should send error message json well.


Comments

Popular posts from this blog

command line - Use qwinsta in PowerShell ISE -

java - Incorrect order of records in M-M relationship in hibernate -

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -