简体   繁体   中英

how to solve Ajax post request show 500 (Internal Server Error) in laravel

In my project i want to store data in to database using ajax but when i submit the post request it show the error like (500 (Internal Server Error)) i google it several time but still same issue this is my ajax code

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

$('#form-insert').on('submit', function(e){
          e.preventDefault();
          var data = $(this).serialize();
          var url = $(this).attr('action');
          var post = $(this).attr('method');
          $.ajax({
            type: post,
            url: url,
            data:{
                   _token: '{!! csrf_token() !!}',
                   data
                 },
            dataType: 'json',
            success:function(data){
              console.log(data)
            }
          })
        })

this is my view

<form method="post" id="form-insert" action="{{ URL::to('item/store')}}">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" class="form-control" name="name">
    </div>
     <div class="form-group">
      <label for="text">Email address:</label>
      <input type="email" class="form-control" name="email">
    </div>
    <div class="form-group">
      <label for="contact_no">Contact No:</label>
      <input type="text" class="form-control" name="contact_no">
    </div>
    <button type="submit" class="btn btn-primary pull-right" id="add">Submit</button>
  </form>

this is my route

Route::post('/item/store', 'AjaxCrudController@store');

this is my controller

public function store(Request $request)
    {
        if($request->ajax()){
            $item = AjaxCrud::create($request->all());
            return response($item);
            //return response($request->all());
        }
    }

You are trying to insert the data you are submitting in your ajax request:

data:{
   _token: '{!! csrf_token() !!}',
   data
}

That means that you are trying to create an AjaxCrud resource containing two keys: _token and data . I suppose that you just want to store the data contained into the data object, that is your serialized form and should contain a name attribute.

So you have multiple solutions, the first one is to create your AjaxCrud resource from the data object:

$item = AjaxCrud::create($request->get('data'));

The other solution is to send only the data you want in your ajaxRequest, and set your CSRF token into the headers of your request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM