Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How to Insert Data using Ajax in Laravel ?

What is AJAX ?

AJAX stands for Asynchronous JavaScript And XML. It is not a programming language. It is a technology for developing better, faster, and interactive Web Applications using HTML, CSS, JavaScript, and XML.

How AJAX works ?

AJAX communicates with the server using the XMLHttpRequest object. The XMLHttpRequest object sends a request for updated page data to the web server, the server process the request, a response is created server-side and sent back to the browser, which then uses JavaScript to process the response and display it on the screen as updated content.

So let’s see an example How to Insert Data using Ajax in Laravel.

Generating Migration :

php artisan make:migration create_ajax_submit_table

Migration Structure :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAjaxSubmitTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ajax_submit', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->longText('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('ajax_submit');
    }
}

Run Migration :

php artisan migrate
Insert Data using Ajax in Laravel

Make Model :

php artisan make:model AjaxSubmit
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AjaxSubmit extends Model
{
    protected $table = 'ajax_submit';
    protected $fillable = ['id','name','email','phone','addess'];
}

Create Blade File : resources/views/contactForm.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Data Submit Through Ajax | 8Bityard</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
          <br/>
         <h3>Contact Form Data Submit Through <b>Ajax Request</b></h3>
         <div class="card">
            <form name="contact" method="post" id="contactForm">
               @csrf
               <div class="alert alert-success d-none" id="msg_div">
                <span id="res_message"></span>
               </div>
               <div class="card-header">Please fill up all the Field's.</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="Name"> Name :</label>
                        <input type="text" class="form-control" id="name" placeholder="Please enter name" required>
                     </div>
                     <div class="col-md-6">
                        <label for="Email">Email :</label>
                        <input type="email" class="form-control" id="email" placeholder="Please enter email" required>
                     </div>
                     <div class="col-md-6">
                        <label for="Phone">Phone :</label>
                        <input type="number" class="form-control" id="phone" placeholder="Please enter phone" required>
                     </div>
                     <div class="col-md-6">
                        <label for="Address">Message :</label>
                        <input type="text" class="form-control" id="message" placeholder="Please enter address" required>
                     </div>
                  </div>
               </div>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
               <br/>
         </div>
         </form>
      </div>
   </body>
</html>
<script>
$('#contactForm').on('submit',function(event){
    event.preventDefault();
    // Get Alll Text Box Id's
    name = $('#name').val();
    email = $('#email').val();
    phone = $('#phone').val();
    message = $('#message').val();

    $.ajax({
      url: "/contact-formstore", //Define Post URL
      type:"POST",
      data:{
        "_token": "{{ csrf_token() }}",
        name:name,
        email:email,
        phone:phone,
        message:message,
      },
      //Display Response Success Message
      success: function(response){
      $('#res_message').show();
        $('#res_message').html(response.msg);
        $('#msg_div').removeClass('d-none');

        document.getElementById("contactForm").reset();
        setTimeout(function(){
        $('#res_message').hide();
        $('#msg_div').hide();
        },4000);
   },
  });
});
</script>

How to Insert Data using Ajax in Laravel

Make a Controller :

php artisan make:controller AjaxSubmitController

Define Routes : web.php

Route::get('/contact-form','AjaxSubmitController@Create')->name('ajax.form');
Route::post('/contact-formstore','AjaxSubmitController@StoreData')->name('ajax.formStore');

Functionality & Logic :

App\Http\Controllers\AjaxSubmitController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\AjaxSubmit;
class AjaxSubmitController extends Controller
{
    public function Create(){
        return view('contactForm');
    }

    public function StoreData(Request $request){
        $contact = new AjaxSubmit;
        $contact->name    = $request->name;
        $contact->email   = $request->email;
        $contact->phone   = $request->phone;
        $contact->message = $request->message;
        $contact->save();
        if($contact){
          #Display Success Message in Blade File
          $arr = array('msg' => 'Your query has been submitted Successfully, we will contact you soon!', 'status' => true);
      }
      return Response()->json($arr);
    }
}

Output :

Insert Data using Ajax in Laravel
Insert Data using Ajax in Laravel

In this article, we learned “How to Insert Data using Ajax in Laravel”, I hope this article will help you with your Laravel Application Project.

Note :

Ajax is not recommended for login authentication and posting forms.

Also Read : Laravel Crud App