Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error 422 Ajax Post using Laravel

I'm trying to make a simple Ajax post using Laravel 5. I read that there is a issue with the Csrf Token matching and that i could put my uri into the VerifyCsrfToken expection to step around this. This part functions, however now I get a 422 error when i make the post.

enter image description here

enter image description here

Did I mess something up in my code? How can I get this working? Here is what I have:

HTML:

<div class = "q-form">
                    {!!Form::open(array('url' => 'questions')) !!}
                        <div class = "form-group">
                            {!! Form::hidden('user_id', $myid, ['class' => 'form-control']) !!}
                            {!!Form::label('title', 'Title:')!!}
                            {!!Form::text('title', null, ['class'=> 'form-control'])!!}

                            {!!Form::label('question', 'Question:')!!}
                            {!!Form::textarea('question', null, ['class'=> 'form-control area', 'placeholder' => 'What would you like to ask?'])!!}


                        {!!Form::submit('Ask!', ['class'=> 'btn btn-danger form-control ask'])!!}
                        </div>
                    {!! Form::close() !!}
                </div>

JS:

$('.ask').click(function(e) {

       e.preventDefault();

       var postData = $(this).serializeArray();

       var base_url = 'http://rem-edu-es.eu1.frbit.net/';
       $.ajax({
           type: "POST",
           url: base_url + "questions",
           data: postData,
           success: function (data) {
               console.log(data);
           }

       });
   });

Controller:

 public function book()
{

    if(Request::ajax()){

        return Response::json(Input::all());

    }
}

VerifyCsrfToken:

  class VerifyCsrfToken extends BaseVerifier
{

    protected $except = [
        'book/*',
        'book',
         'questions'

    ];
}
like image 817
Ricki Moore Avatar asked Feb 08 '23 23:02

Ricki Moore


2 Answers

Error handling an object within response.

error :function( data ) {
        if( data.status === 422 ) {
            var errors = $.parseJSON(data.responseText);
            $.each(errors, function (key, value) {
                // console.log(key+ " " +value);
            $('#response').addClass("alert alert-danger");

                if($.isPlainObject(value)) {
                    $.each(value, function (key, value) {                       
                        console.log(key+ " " +value);
                    $('#response').show().append(value+"<br/>");

                    });
                }else{
                $('#response').show().append(value+"<br/>"); //this is my div with messages
                }
            });
          }

enter image description here

like image 53
Harry Bosh Avatar answered Feb 11 '23 15:02

Harry Bosh


422 is a default response when validation fails. When you processing ajax response, you need to process "success" and "error". Example from my code:

$.ajax({
    url: $(this).data('url'),
    type: "post",
    dataType: "json",
    data: values,
    success: function (data) {
        $('#list').append(data.view);
    },
    error: function (data) {
        var errors = $.parseJSON(data.responseText);
        $.each(errors, function (key, value) {
            $('#' + key).parent().addClass('error');
        });
    }
});

By the way, you can pass a _token parameter with your ajax post, then you don't need to disable CSRF protection. Just add a hidden input

{!! Form::token() !!}

in your form that you send to a server via ajax.

like image 29
Victor Levandovski Avatar answered Feb 11 '23 13:02

Victor Levandovski