dev_varma19
dev_varma19

Reputation: 23

How to fix Laravel AJAX request not working

I am trying to store the data from multiple ratio buttons to the database. And the AJAX post request is below:

$.ajax({  
                url: '{{ route("checklist.store") }}',  
                method:'POST',  
                data:{
                    _token: CSRF_TOKEN,
                    data1 : value1,
                    data2 : value2
                    },  
                success:function(data){  
                    console.log('success');
                }  
            });

The message in the console is printed on the console but the item is not created in the database.

Store method in controller :

    $hacInspectionsChecklistTable = HacInspectionsChecklistTable::create($request->all());

    

Upvotes: 2

Views: 357

Answers (1)

therealwalim
therealwalim

Reputation: 291

Check your Model first :

protected $fillable = [
 'data1', 'data2'
];

If everything is ok you can try with something like that

Ajax code :

$.ajax({  
   url: '{{ route("route.store") }}',  
   method:'POST',  
   data:{
         _token: CSRF_TOKEN,
         data1 : value1,
         data2 : value2
        },  
        success:function(data){  
          if(data=="created"){
            console.log('success');
          }
        }  
});

Route

Route::post('/youroute', [YourController::class, 'store'])->name('route.store');

Controller

public function store(Request $request){
    $data = new Model();
    $data->data1 = $request->data1;
    $data->data2 = $request->data2;
    $data->save();

    return response()->json('created');
}

Upvotes: 1

Related Questions