lundi 12 octobre 2015

Laravel, jQuery, AJAX - 422 response, iterate through JSON

This is my script:

    $("#previewModalWindowBtn").click(function (e) {
        e.preventDefault();
        var route = '{{ route('order-ajax-validate') }}';
        var token = $('meta[name="csrf-token"]').attr('content');
        var data = $("#orderForm").serialize();
        $.ajax({
            type: 'POST',
            url: route,
            headers: {'X-CSRF-TOKEN': token},
            dataType: 'json',
            data: data,
            success: function(){
                $("#previewModalWindow").modal('show');
            },
            error: function(data){
                var errors = data.responseJSON;
                console.log(errors);
                $("#previewOrder").modal('hide');
                alert('Need to fill the required fields');
                // Iterate through JSON and add error classes to fields with errors
            }
        });
    });

And what I get when I open console is 422 Unprocessable Entity:

    {
    "category.subcategory_one":["Some error message depending why the validation failed."],
    "category.subcategory_two":["Some error message depending why the validation failed."]
    }

I don't quite understand the structure here but if I got everything right this should be JSON response. What I need is to iterate through these key->value pairs and add error classes to the right elements.

My question is: How do I reach this JSON in my script and how do I iterate (I suppose I'll use .each for iteration) through these values.

Other thing is that my inputs have names of type:

    <input name="category[subcategory_one]" />
    <input name="category[subcategory_two]" />

and so on and the response is formatted as category.subcategoy_one. I think this could be Laravel thing and not necessary connected to the original question but I also don't know how to solve it at the moment.

Thank you.

ps. I have found this:

How do I show JSON HTTP 422 responses to the user when using jQuery ajax?

which could be a solution to my problem but I need a little more help with explanation on what to do.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire