javascript - Errors while parsing invalid JSON passed from PHP to AJAX -


i'm trying parse json sent php.

json:

[{"id":"1","value":"1"},{"id":"4","value":"1"},{"id":"2","value":"1"},{"id":"3","value":"1"},{"id":"4","value":"1"}] 

i'm trying parse id , pass javascript function , i'm continuously calling php. when tried $.ajax, $.get, $.getjson , used json.parse , parsejson, error:

uncaught syntaxerror: unexpected token <

because json looks this:

id: id: id: html> 1id: 4id: 1id: 2id: 3id: 4id: id: id: > 

i tried fix using json.stringify, caused error:

cannot use 'in' operator search 'length' in , i'm stuck , have no idea how fix this.

test.php:

<?php   $link = mysql_connect("localhost", "root", "password");    if (!$link) {     die('could not connect: ' . mysql_error());   }    $db = mysql_select_db("example");    $sql = "select * data";   $x = mysql_query($sql);    $emparray = array();   while ($row = mysql_fetch_assoc($x)) {     $emparray[] = $row;   }   echo json_encode($emparray);    mysql_close($link); ?> 

heatmap.html:

<script>         $(window).ready(function(){           $.ajax({             url:'test.php',             data:"{'id':'1', 'value':'1'}",              contenttype: "application/json; charset=utf-8",             datatype: 'json',              success: function (data){setinterval(function(){              /* if use parsejson(data), "unexpedted token <"                error */               $.each(data, function (id, value){ // error occures here                 liveheatmap(id); //never called               });            }, 10000)}});         }); </script> 

i think problem json invalid. have tried many things , looked @ many other similar problems still cannot fix it.

remove contenttype , datatype properties in ajax request, , use object (rather string) data. in success function, remove setinterval , manually parse json string returned using json.parse(data). ensures have control on data prevent jquery causing problems (and makes clearer). jquery may interfering data in process , want complete raw data.

it looks you're receiving html. common causes:

  • your ajax url pointing incorrect place (and may not seem obvious -- try ./test.php or using absolute path).
  • your php not killed after echoing json. replace mysql_close($link) die() when script ends, database connections automatically closed anyway.

if you're still having issues, run these commands , comment output:

console.log(data); console.log(typeof data); 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -