欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel validate ajax 这几个有大用 明天要细看

https://laracasts.com/discuss/channels/general-discussion/showing-request-validation-errors-when-sub...
https://laravel.com/docs/master/validation#quick-ajax-requests-and-validation
http://stackoverflow.com/questions/17097797/validation-errors-in-ajax-mode
http://laravel.io/forum/10-24-2015-laravel-5-and-ajax
https://laracasts.com/discuss/channels/general-discussion/laravel-5-ajax-error-handling-with-request...
https://laracasts.com/discuss/channels/general-discussion/showing-request-validation-errors-when-sub... 422例子 又好像401是无权访问 有大用  
http://stackoverflow.com/questions/28379023/laravel-5-ajax-post 422例子
http://stackoverflow.com/questions/28858575/laravel-ajax-validation 422例子
http://stackoverflow.com/questions/31891347/laravel5-csrf-filter-return-http-422-error 422表单验证错误例子 403无权访问
https://gist.github.com/thepsion5/d7f43f183b500bb3afc5
http://codereview.stackexchange.com/questions/74420/laravel-controller-for-form-validation-skinny 422例子


Showing request validation errors when submitting form by ajax

haakym
haakym card_membership — 1 year ago

Hey everyone,

I'm writing a new project in Laravel 5 and submitting a form by ajax and I'm using a request to validate the form.

I can't quite figure out how to grab the error message data using javascript if the validation fails. As it mentions in the documentation: "If the incoming request was an ajax request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors." -http://laravel.com/docs/5.0/validation#controller-validation

Any ideas how I can get access to the data returned to the browser if a validation error occurred?

Best Answer — Thread Owner's Choiceschool

pmall
pmall — 1 year ago

If an ajax request don't pass a form request validation, errors will be returned as json. You can catch them in the error callback of jquery ajax method :

    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(data){
        // success logic
      }),
      error: function(data){
        var errors = data.responseJSON;
        console.log(errors);
        // Render the errors with js ...
      }
    });
pmallcheck
 pmall — 1 year ago

If an ajax request don't pass a form request validation, errors will be returned as json. You can catch them in the error callback of jquery ajax method :

    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(data){
        // success logic
      }),
      error: function(data){
        var errors = data.responseJSON;
        console.log(errors);
        // Render the errors with js ...
      }
    });
usman
usman — 1 year ago

If you are posting a form using jQuery ajax you can use the error handler to grab the error data e.g:

...
....
error :function( jqXhr ) {
        if( jqXhr.status === 401 ) //redirect if not authenticated user.
            $( location ).prop( 'pathname', 'auth/login' );
        if( jqXhr.status === 422 ) {
        //process validation errors here.
        $errors = jqXhr.responseJSON; //this will get the errors response data.
        //show them somewhere in the markup
        //e.g
        errorsHtml = '<div class="alert alert-danger"><ul>';

        $.each( data, function( key, value ) {
            errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
        });
        errorsHtml += '</ul></di>';
            
        $( '#form-errors' ).html( errorsHtml ); //appending to a <div id="form-errors"></div> inside form
        } else {
            /// do some thing else
        }
    }
....

Usman.

Ozan
 Ozan — 1 year ago

@usman I am pretty sure there is a problem on that code... Where does this data come from in the$.each function?

rashidul0405
rashidul0405 — 1 year ago

@Ozan just a typo, it would be $errors instead of data

Ozan
 Ozan — 1 year ago

@rashidul0405 well it still doesn't work because in my case $errors is always undefined.

jciocci
jciocci — 1 year ago
error :function( jqXhr ) {
        if( jqXhr.status === 401 ) //redirect if not authenticated user.
            $( location ).prop( 'pathname', 'auth/login' );
        if( jqXhr.status === 422 ) {
        //process validation errors here.
        var errors = jqXhr.responseJSON; //this will get the errors response data.
        //show them somewhere in the markup
        //e.g
        errorsHtml = '<div class="alert alert-danger"><ul>';

        $.each( errors , function( key, value ) {
            errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
        });
        errorsHtml += '</ul></di>';
            
        $( '#form-errors' ).html( errorsHtml ); //appending to a <div id="form-errors"></div> inside form
        } else {
            /// do some thing else
        }
    }
jciocci
jciocci — 1 year ago

This is my code using toastr notifications:

var form = $("#editForm");

    $.ajax({
        url     : form.attr("action"),
        type    : form.attr("method"),
        data    : form.serialize(),
        dataType: "json",
        success : function ( json ) 
        {
            toastr.success( json.message , "Notifications" );
        },
        error   : function ( jqXhr, json, errorThrown ) 
        {
            var errors = jqXhr.responseJSON;
            var errorsHtml= '';
            $.each( errors, function( key, value ) {
                errorsHtml += '<li>' + value[0] + '</li>'; 
            });
            toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
        }
    })
    .done(function(response)
    {
        //
    })
    .fail(function( jqXHR, json ) 
    {
        //
    });
    return false;
HashmatWaziri
 HashmatWaziri — 4 months ago

//controller method

        $validation = \Illuminate\Support\Facades\Validator::make($request->only('start_date', 'end_date'),    $rules);

    if($validation->passes())

    {
        $update                   = Lecturer::find($id);
        $update->status           = $request->get('status');
        $update->start_date       = $request->get('start_date');
        $update->end_date         = $request->get('end_date');
        if($update->save()) {

        return response()->json([
                'success' => true,
                'message' => 'record updated'
            ], 200);

        }
    }
    $errors = $validation->errors();
    $errors =  json_decode($errors); 

    return response()->json([
        'success' => false,
        'message' => $errors
    ], 422);

// view

                   $.ajax({
                    url: URL,
                    type: 'PUT',
                    data: formdata,
                    success: function (response) {
                    window.location = "{{ URL::route('campaign.index')}}";
                      },

                    error: function(xhr,status, response) {
                        var error = jQuery.parseJSON(xhr.responseText);  // this section is key player in getting the value of the errors from controller.
                        var info = $('.edit_alert');
                        info.hide().find('ul').empty();
                            for(var k in error.message){
                                if(error.message.hasOwnProperty(k)){
                                    error.message[k].forEach(function(val){
                                        info.find('ul').append('<li>' + val + '</li>');
                                    });

                                }
                            }

                           info.slideDown();


                }

                });
eflames
eflames — 3 months ago

I just did this an works

            error: function(data)
            {
                var errors = '';
                for(datos in data.responseJSON){
                    errors += data.responseJSON[datos] + '<br>';
                }
                $('#response').show().html(errors); //this is my div with messages
            }

So, when the request fails, the error method prints the messages from Laravel Validation system on my div .

Btw sorry for my english :D

来自  https://laracasts.com/discuss/channels/general-discussion/showing-request-validation-errors-when-sub...


普通分类: