0

I have the following jQuery Code:

$.post('php/php_result.php', {'functions':'getpersonaldetails','theuserid':data1}, function(data3, status3) {
    var personalDetails = JSON.parse(data3)[0];
    alert(personalDetails.last_name);           
},'json');

The above code has en Syntax Error: JSON.parse: unexpected chacter at line1 column 2 of the JSON data. If I remove the datatype json, the alert works fine.

My PHP:

$queryStmt = "SELECT merch_id, last_name, first_name, middle_name, birthday, contact_no, address FROM merchandiser WHERE merch_id=:userId";
$queryPrepare = $dba_connect->prepare($queryStmt);
$queryPrepare->execute(array(':userId'=>$_POST['theuserid']));
$queryResult = $queryPrepare->fetchAll(PDO::FETCH_ASSOC);
$queryPrepare->closeCursor();
$jsonResponse = json_encode($queryResult);
echo $jsonResponse;

Why am I having error when I indicate json as my datatype?

PaulPolon
  • 319
  • 1
  • 5
  • 17

1 Answers1

1

If you instruct jQuery to expect JSON, it'll decode it for you automatically:

"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.

Thus parsing it again is not going to work.

Just let the framework do the job for you.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360