JSON.parse: unexpected character
I am trying to pass json from php jquery, after hitting the sql query array and getting the following javascript error.
JSON.parse: unexpected character
The sql result return function:
public function selectassocSql($sql){
$i = 0;
$resSelect = array();
mysql_query("SET NAMES 'utf8'");
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) )
{
$resSelect[$i] = $row;
$i++;
}
mysql_free_result($result);
return $resSelect;
}
After using this function,
$sql = "SELECT id, code, name FROM table WHERE code LIKE '%$codcli%' ";
$v = $data->selectassocSql($sql);
echo json_encode($v, JSON_FORCE_OBJECT);
And the javascript code is like this:
$('#formclientes').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = $.parseJSON(data);
}
})
})
How can I fix this error and how can I read json from jquery?
source to share
You don't need a call $.parseJSON
as jQuery does this automatically because if you don't specify a property dataType
jQuery tries to guess it and calls the correct function to parse the response before the data is processed by the success function
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = data;
}
})
Also check this question Why is "jQuery.parseJSON" not required?
source to share
I just ran into this in FF10.0.2 with data that looked like this:
[ { "firstName": 'Joe', "lastName": 'Smith' } ]
(with multiple objects in an array - short for clarity)
It actually parsed OK using eval instead of JSON.parse. (I am not using jQuery here.)
The problem went away when I changed the "to" for values:
[ { "firstName": "Joe", "lastName": "Smith" } ]
I thought the “requirement is only for property names, not data values.
source to share