Mohini
Mohini

Reputation: 268

issue with ajax post in laravel

I am making one state module for which I want to make create state popup

and for that I have make below code

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(document).on('click', '#save_state_detail', function() {
        
    var url_variable = '{{ route("admin.state.store") }}';
    $.ajax({
            type: 'POST',
            url: url_variable,
            async: false, 
            data: $('#state_form_add').serialize(),
            contentType: "application/json",
            success: function (data) {
                console.log(data);
            },
            error: function(data){
                if(data.status === 422)
                {
                    $('.error').html('');
                    var errors = data.responseJSON;
                    $.each( errors.errors, function( key, value ) {
                        $('#error_'+key).html(value);   
                    });
                }
            },
        });
});
<!-- Latest compiled and minified CSS -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div>
    <button type="button" class="btn btn-primary btn-flat" data-toggle="modal" data-target="#form">
    <i class="fa fa-plus" aria-hidden="true"></i> &nbspNew State
    </button>  
</div>


<div class="modal fade" id="form" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header border-bottom-0">
                <h5 class="modal-title" id="exampleModalLabel">Add State</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            
            @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
            
            <form role="form" action="javascript:void(0)" method="post" id="state_form_add">
            @csrf
            <div class="box-body">
                
            <div class="form-group">
                <label for="exampleInputEmail1">State Name <span style="color:red;">*</span></label>
                <input type="Text" class="form-control" id="exampleInputEmail1" placeholder="State Name" name="name" value="{{ old('name')}}">
            </div>
            
            </div>
            <!-- /.box-body -->
            <div class="box-footer">
                <button type="submit" id="save_state_detail" class="btn btn-primary">Submit</button>
            </div>
        </form>
        </div>
    </div>
</div>

Route::group(['prefix' => 'admin', 'as' => 'admin.','middleware' => ['auth']],function(){
    Route::resources([
       'state' => 'Admin\StateController',
    ]);
});

and make controller

public function store(StateRequest $request)
{
    $create = new StateModel();
    $result = $create::create([
        'name' => $input['name']
    ]);
    if($result){
        $data_info = [
            'msg' => 'Success',
            'error' => 0
        ];
    }else{
        $data_info = [
            'msg' => 'Something wend wrong',
            'error' => 1
        ];
    }
    return response()->json($data_info);
}

and add rules in request file

public function rules()
{
    app()->getLocale();
    return [
        'name' => 'required'
    ];
}

with above code if I fill data in input box it is correctly inserted in database but if I submit form with blank input it is showing me error 422 Unprocessable Entity Explained

can anybody help me with this my request file's path is correct but issue with validation response

Upvotes: 0

Views: 102

Answers (1)

Dimitri Mostrey
Dimitri Mostrey

Reputation: 2355

Try this:

$(document).on('submit', 'form#state_form_add', function(e) {
    e.preventDefault();
    let name = $('#exampleInputEmail1').val();
    $.ajax({
            type: 'POST',
            url: '{{ route("admin.state.store") }}',
            data: { name },
            success: function (data) {
                console.log(data);
            },
        });
});

And the opening of your form should be <form id="state_form_add">. Nothing more is needed. Apart from missing bootstrap classes. But that has nothing to do with your 422 error. Keep the ajax setup header. Of course.

Upvotes: 1

Related Questions