I am sending a JSON object to a PHP file, The PHP does some manipulation and returns a JSON string:
$('button#indexOpener').on('click', function() {
var aUsername = $('input#edUsername').val();
var aPassword = $('input#edPassword').val();
if (($.trim(aUsername) != '') && ($.trim(aPassword) != '')) {
var str = $("#form_login :input").serializeArray();
$.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
alert(data.edUsername);
});
}
else {
alert('Please insert a valid username and password');
alert("<?php echo URL; ?>/ajax");
}
});
the PHP echoes a JSON object:
echo json_encode($_POST);
but when I try to alert the data with jQuery:
function(data) {
alert(data.edUsername);
}
is displaying the message undefined. I am sure it is something stupid but I cannot see what I am doing wrong, can you help?
I see no dataType set for
$.post(). jQuery will try to recognize returned content type, but you need to set correct headers. So, you need to add:before
echo json_encode, or you should set dataType:”json” in JS code (fourth parameter of$.post()):This way, jQuery will know that the data returned is in JSON format and should be parsed. Without it, jQuery will check the
Content-Typeheader and apply parser according to it. Suppose if no custom content type headers set, it will return return data as HTML. Actually, that is a usual string.JSON is a regular string which should be parsed on client side. jQuery detects your response as plain text or HTML and does not parse JSON to Javascript object. In case of data being an object, you would get [object Object] in alert window.