UPDATE
So the JQuery.post() function receives valid JSON. I know the attribute "json" in the function call should already be enough to get the original array and .parseJSON() is not necessary. I guess that's why I get the syntax error when using this function.
But somehow I still can't access the array without the .parseJSON(). In fact, when I use typeof(data) it's still a string. I can write it to the console and it's still valid JSON.
How do I use my array (originally associated PHP array encoded once via json_encode()) as normal associated array in JavaScript?
ORIGINAL POST
I've been getting this syntax error for days and it's driving me crazy. I read a lot of posts and I know it must be a super simple thing I'm missing. Please help. Thanks in advance.
var institute = $.post("../libraries/load_content.php",
{
funct: "getInstituteAddress",
ins_name: "Institut für Informatik",
ins_city: "Kiel"
}, "json");
institute.done(function(data) {
alert(data);
var ins_data = $.parseJSON(data); // <-- throws syntax error
$("#street").empty().val(ins_data['ins_street']);
$("#number").empty().val(ins_data['ins_number']);
$("#postalcode").empty().val(ins_data['ins_postal_code']);
}, "json");
institute.fail(function(data) {
console.log("Retrieving institute data failed. Returned:"+data);
});
The JQuery.post() function calls a php script, which fetches the required data from the DB and returns an associative array with json_encode().
This works fine till this point.
{"ins_name": "Institut für Informatik",
"ins_street": "HRSl",
"ins_number": "42",
"ins_postal_code": "24118",
"ins_city": "Kiel"}
Above I alert the returned String and the JSONLint validator tells me it's valid JSON.
So I copied the String directly into the parseJSON() call. Worked fine. Why not with the variable?
Here's what I tried:
- I often read about missing single/double quotes. No luck here. Added them in multiple variations acound the String.
- I also often read that the parseJSON function is not required in such environment. So I dropped the function call. The syntax error of course disappears, but the I can't read the JSON as normal array so the fields are just emptied.
- I tried replacing the .post() function by .ajax(), adding the missing arguments... with the same effect.
- I changed the dataType attributes to html or text. Again no luck.
, 'json');
to your$.post
call. This tells jQuery to parse the JSON for you. Yourdata
parameter is already an object, no need to use$.parseJSON
. – Rocket Hazmat Aug 23 '13 at 16:37console.log(data)
(alert
is not a very good debugging tool). – Rocket Hazmat Aug 23 '13 at 16:37