UAMoto
UAMoto

Reputation: 271

Iterate json through $.each function TypeError

I get the response from php as:

{"success":false,"errors":{"category_id":"category id must not be empty","name":"name must not be empty","uri":"uri must not be empty","price":"price must not be empty","status":"status must not be empty"}}

and want to display the errors:

form.submit(function(ev) {
    ev.preventDefault();

    $('.help-inline').remove();

    var data = $(this).serialize();

    $.post($(this).attr('action'), {'data': data}, function(result) {

        if (result.success == true) {
            console.log('true');
        } else {
            $.each(result.errors, function(label, error) {
                console.log(label+' '+error);
            });
        }
    });
});

But it throws me TypeError: e is undefined

On older versions it works, but on 1.8.3 is not. What I'm doing wrong?

My php code is:

            $errors = $post->errors('');
            $this->response->body(json_encode(array(
                'success' => FALSE,
                'errors' => $errors,
            )));

$errors is associative array:

array(5) (
    "category_id" => string(29) "category id must not be empty"
    "name" => string(22) "name must not be empty"
    "uri" => string(21) "uri must not be empty"
    "price" => string(23) "price must not be empty"
    "status" => string(24) "status must not be empty"
)

Upvotes: 0

Views: 910

Answers (3)

Aivar
Aivar

Reputation: 2029

PHP and response seems to be ok, but i do not see where you will say for javascript that you will use json data type. You can verify that when you use console.log(result) code. And see if your result is an object or string. As

form.submit(function(ev) {
    ev.preventDefault();

    $('.help-inline').remove();

    var data = $(this).serialize();

    $.post($(this).attr('action'), {'data': data}, function(result) {
        console.log('Result is: ' + typeof(result));
        if (result.success === true) {
            console.log('true');
        } else {
            $.each(result.errors, function(label, error) {
                console.log(label+' '+error);
            });
        }
    });
}, "json");

Upvotes: 0

MrCode
MrCode

Reputation: 64536

In your JSON, your errors array appears to only ever contain a single element which is an object with properties, try using:

$.each(result.errors[0], function(label, error) {

Upvotes: 0

Your result.errors is an array with just one element, the one you want to iterate with $.each , so just replace your following line:

$.each(result.errors, function(label, error) {

for this one:

$.each(result.errors[0], function(label, error) {

that should do what you want.

Upvotes: 2

Related Questions