I have 2 php files: index and page. In index.php I write ajax/jquery code:
$(document).ready( function () {
var mas;
$.ajax({
url: "page.php",
type: "POST",
data: "a=aaa&b=bbb",
success: function (htm) {
mas = htm;
alert(htm);
}
});
$(document).on("click", function () {
alert(mas['a']);
});
});
In page.php i have only this code:
echo json_encode($_POST);
Data sends successfully, because I obtain in alert message: {"a":"aaa","b":"bbb"}. When I click on document, alerts : "undefined", please tell, where have I wrong? I want that alert "aaa"
The json_encode()
function, does just that...encodes data as JSON. JSON is not a javascript object, it is notation for a javascript object. In order to use it as an object, you need to first parse it:
mas = JSON.parse(htm);
Then you can access values like:
alert(mas.a);
Add:
header('Content-type: application/json');
to the top of the PHP script.
Your JSON data is being treated as an HTML string and not inflated into a JavaScript object.
You need to tell jQuery to parse the JSON from the AJAX call. To do this add dataType: 'json'
to $.ajax
.
$.ajax({
url: "page.php",
type: "POST",
data: "a=aaa&b=bbb",
dataType: 'json',
success: function (htm) {
mas = htm;
console.log(htm);
}
});