So I've been reading up on a few guides on using json to return values to JS from php. I've however encountered a bit of a problem. Right now, I've got a jquery-function (don't get distracted with 'id: 1', it's used for something else), such as:
$('#some_trigger').on('change', function(){
$.post("retrieve.data.php", {
id: 1
}, function (data) {
var values = data;
alert(values[name]);
});
});
And on the receiving end (in 'retrieve.data.php'), I've got:
$arr_assoc_template = array(
"name" => "aName",
"id" => "anId"
);
echo json_encode($arr_assoc_template, JSON_PRETTY_PRINT);
However, the console and alert window keeps logging [name] as undefined. What am I missing? :(
Use JSON.parse
, turns a string of JSON text into a Javascript object.
var values = $.parseJSON(data);
console.log(values.name);
You are missing double quotes around the name
in values["name"]
Or you can use values.name
. The first option is better practice.