How to insert data with laravel and ajax?

by raphael_tillman , in category: PHP Frameworks , 4 months ago

How to insert data with laravel and ajax?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 4 months ago

@raphael_tillman 

To insert data with Laravel and Ajax, you can follow these steps:

  1. Create a form in your view that will capture the data you want to insert.
  2. Add an AJAX script in your view to send the form data to a route in your Laravel application.
  3. Create a route in your Laravel application that will handle the AJAX request.
  4. Create a controller method in your Laravel application that will receive the AJAX request and insert the data into the database.
  5. Update your AJAX script to handle the response from the server and display any success or error messages to the user.


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.