I'm trying to send an associative array from PHP to Javascript. But, for some reason, the output is Undefined. Here's the code:
PHP (Suppositional array):
$validationErrors = array("unregisteredName" => NULL,
"unregisteredEmail" => "Invalid e-mail", "unregisteredUsername" => NULL,
"unregisteredPassword" => NULL);
$log = array("errors" => $validationErrors);
echo json_encode($log);
Javascript:
var addUserCallback = function(data) {
if(data.errors && data.errors.length) {
$.each(data.errors, function(index, error) {
console.log(error);
$("#"+index).attr("placeholder", error);
});
}
else {
window.location="/users/success/";
}
};
var errorCallback = function(xhr, status, error) {
console.log(arguments);
};
self.addUser = function() {
var data = {
unregisteredName: $("#unregisteredName").val(),
unregisteredEmail: $("#unregisteredEmail").val(),
unregisteredUsername: $("#unregisteredUsername").val(),
unregisteredPassword: $("#unregisteredPassword").val()
};
$.post(addUserUrl, data).success(addUserCallback)
.error(errorCallback);
}
And here is what I get from Chrome's Inspector:
data: "↵{"errors":{"unregisteredName":null,"unregisteredEmail":"Invalid e-mail.","unregisteredUsername":null,"unregisteredPassword":null}}"
data.errors: Undefined
So, what's happening is that, even getting data on "data" variable, because of the fact that it is unformatted it always redirects to the "success" page.
Any ideas?
datais a string. You need to parse the JSON string and extract your object first.