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?

3
  • var personalDetails = data3[0]; Commented Apr 10, 2017 at 9:05
  • @Tomalak it's not about posting json data to somewhere.It's about parsing json response into jQuery post coming from server.Please read question once. Commented Apr 10, 2017 at 9:12
  • Then this is your duplicate. stackoverflow.com/questions/4064444/… Commented Apr 10, 2017 at 10:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.