jqueryajaxlaravel-5.8extract-error-message

Display response json messages in a div using jquery in laravel


I have a form to change my password. I need to display error messages in a div.

The response that I am getting from controller is as follows

{"errors":{"current_password":"validation.reset.current_pass_not_match"}}

My blade

<form action="{{ route('admin.reset.password') }}" method="POST" name="popUpChangePwd" id="popUpChangePwd">

              {{ csrf_field() }}
            <div class="form-group row">
                <label class="col-sm-4 col-form-label ">Current Password
                </label>
                <div class="col-sm-8">
                    <input class="form-control mb-0" name="current_password" id='current_password' type="password">
                    <div class="error" id="demo"></div>

                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label ">New Password
                </label>
                <div class="col-sm-8">
                    <input class="form-control mb-0" name='new_password' id='new_password' type="password">

                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-4 col-form-label ">Confirm Password
                </label>
                <div class="col-sm-8">
                    <input class="form-control mb-0" name='confirm_password' id='confirm_password' type="password">

                </div>
            </div>
            <div class="form-group row">
                <label class="col-sm-6 col-form-label text-left text-lg-right"></label>
                <div class="col-sm-6 text-right">
                    <button type="submit" class="btn btn-primary">SUBMIT</button>
                </div>
            </div>
        </form>

My controller function

 public function postPassword(ResetPassword $request)
{       
       $inputDetails = $request->validated();
       $curr = $request->current_password;
       $login_user = Auth::guard('admin')->user()->id; 
       $new_pass = bcrypt($request->new_password);
       if (Hash::check($curr,Auth::guard('admin')->user()->password)) 
       {
           $update_user_pass = DB::update('update users set password =? where id = ?',[$new_pass, $login_user]);
           if ($update_user_pass) 
           {
                //return redirect()->back()->with('message', 'Password updated successfully');
               return response()->json(['error' => 0, 'code' => 200, 'message' => "Password changed successfully",'redirect' => true, 'url' => route('admin.profile')], 200);
           } 
       }
       else 
       {               
         return response()->json(['errors'=>['current_password'=> trans('validation.reset.current_pass_not_match')]], 422);          

       }
}

My validation code

$(document).on('submit', '#popUpChangePwd', function (e) {        
        e.preventDefault();  

        var url         = this.action;   

        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(this),
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,       
            success: function (response) {                 

                if(!response.error){
                                    showAlert($('.message-alerts'),'success',response.message);
                                    $(form).find('[name="current_password"]').val('');
                                     $(form).find('[name="new_password"]').val('');
                                     $(form).find('[name="confirm_password"]').val('');

                                     } else {

                                         showAlert($('.message-alerts'),'danger',response.message);  
                                     }                
            },
            error: function (response) {

                showValidation(response);
            }
        });        
        return false;         
    });

    function showValidation(response) {alert(response.responseText);
        var errTextboxClass = 'error';
        var errMsg = '';
        var j = 0;
        var respArray = JSON.parse('response.responseText').errors;     
        $('.' + errTextboxClass).remove();
        $.each(respArray, function (k, v) {            
            j = parseInt(j) + 1;
            var $this = $('#' + k); 
            $('#' + k).after('<div class="' + errTextboxClass + '">' + v .message+ '</div>');  
            if (j == 1)
                $('#' + k).focus();
        });
    }

In alert I am getting the response,but fail to extract the error message to my div. Thanks in advance.


Solution

  • Ok, so I got the mistake in my above code.

    function showValidation(response) {
            var errTextboxClass = 'error';
            var errMsg = '';
            var j = 0;
            var respArray = JSON.parse(response.responseText).errors;       
            $('.' + errTextboxClass).remove();
            $.each(respArray, function (k, v) {            
                j = parseInt(j) + 1;
                var $this = $('#' + k); 
                $('#' + k).after('<div class="' + errTextboxClass + '">' + v+ '</div>');  
                if (j == 1)
                    $('#' + k).focus();
            });
        }
    

    I was trying to display v.message which is actually undefined. So remove the .message