0

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?

1
  • Because data is a string. You need to parse the JSON string and extract your object first. Commented Jan 6, 2012 at 20:13

1 Answer 1

6

You need to tell jQuery to parse the JSON string.

$.post(addUserUrl, data, 'json').success(addUserCallback).error(errorCallback);

Though I usually pass the success callback to $.post

$.post(addUserUrl, data, addUserCallback, 'json').error(errorCallback);
Sign up to request clarification or add additional context in comments.

4 Comments

Alternatively -- really, when not using jQuery AJAX as so -- look up "JSON.parse".
I also recommend setting application/json as the content type when you return JSON (that way jQuery might be able to figure it out without the datatype - but better do both).
WAY easier than I thought. I did tried to put "json" in $.post, but I was passing the success callback outside... Probably it wasn't understanding the parameters. Thank you very much.
@Falassion: You're welcome. I've never used .success, I guess it acts differently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.