@raphael_tillman
To insert data with Laravel and Ajax, you can follow these steps:
Here is an example of how you can achieve this:
In your view file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<form id="insertForm"> <input type="text" name="name" placeholder="Name"> <input type="email" name="email" placeholder="Email"> <button type="submit">Submit</button> </form> <script> $('#insertForm').submit(function(e){ e.preventDefault(); var formData = $(this).serialize(); $.ajax({ url: '/insert-data', type: 'POST', data: formData, success: function(response){ console.log(response); }, error: function(err){ console.log(err); } }); }); </script> |
In your routes file:
1
|
Route::post('/insert-data', 'DataController@insertData'); |
In your controller:
1 2 3 4 5 6 7 8 9 10 |
use AppModelsData; public function insertData(Request $request){ $data = new Data; $data->name = $request->input('name'); $data->email = $request->input('email'); $data->save(); return response()->json(['message' => 'Data inserted successfully']); } |
Remember to replace Data
with your actual model name, and make sure to have the necessary validation and error handling in your controller method.