donnah
donnah

Reputation: 43

I cant insert data to db using ajax in laravel 5.2

I wonder if its because of the model, and I dont know where to put model file and what to write on it, im new to laravel 5.2

html (testing.blade.php)

<input type="text"id="name" name="name">
<button type="submit" id="add">ADD</button>

ajax

    $("#add").click(function() {
        $.ajax({
            type: 'post',
            url: 'addItem',
            data: {
                '_token': $('input[name=_token]').val(),
                'name': $('input[name=name]').val()
            },
            success: function(data) {
                alert(data);
            },
        });
        $('#name').val('');
    });

routes

Route::post ('test', 'CommentsController@addItem' );

controller

public function addItem(Request $request) {
    $data = new Comments ();
    $data->comment = $request->name;
    $data->save ();
    return response ()->json ( $data );
}

Upvotes: 1

Views: 1186

Answers (1)

Peter Kota
Peter Kota

Reputation: 8350

  • You need to add the csrf field and send this value to the server.
  • The ajax url need to match with the route element (not with the controller function name)

BLADE:

{{ csrf_field() }}
<input type="text" id="commentName" name="commentName">
<button type="submit" id="add">ADD</button>

AJAX:

$("#add").click(function() {
  $.ajax({
    type: 'post',
    url: '/add-item',
    data: {
      '_token': $('input[name="_token"]').val(),
      'name': $('input[name="commentName"]').val()
    },
    success: function(data) {
      alert(data);
    },
  });
  $('#name').val('');
});

ROUTE:

Route::post ('add-item', 'CommentsController@addItem');

Documentation regarding to CSRF Protection.

Upvotes: 1

Related Questions