How to Use Ajax in Laravel 10

AJAX is the way to communicate between client and server without page refresh. It is the technique of passing data from one server to another without interruption.

Visual Representation of AJAX Request

The syntax of the jQuery Ajax is the following.

jQuery.ajax( url [, settings ] )

How to Use Ajax?

To use Ajax, you need jQuery to send a network request without a page refresh to the server. The Ajax request can be GET, POST, or other valid types.

Import a jQuery library in your view file to use the Ajax functions of jQuery, which will be used to send and receive data using Ajax.

On the server side, you can use the response() function to send the response to the client, and to send a response in JSON format; you can chain the response function with the json() function.

If the request is POST, then using the jQuery ajax() or post() method, we will send a request to the server to store the form values in the database.

Here is the step-by-step guide using AJAX in Laravel 10.

Step 1: Install and configure Laravel.

You can install Laravel with the following command.

composer create-project laravel/laravel lara10 --prefer-dist

It will Install Laravel 10. You can see the screenshot below.

Install and configure Laravel 10

After installing Laravel, we need to configure the database. You can set your database credentials in the .env file.

We build a simple Grocery Application where the user can add the item. So, first, we need to develop the schema for that. Then, to generate a migration file, we need to type the following command.

php artisan make:migration create_groceries_table

It has generated the migration file; now define its columns.

 public function up(): void
 {
   Schema::create('groceries', function (Blueprint $table) {
     $table->id();
     $table->string('name'); 
     $table->string('type'); 
     $table->integer('price');
     $table->timestamps();
   });
 }

Now, migrate the table into our database.

php artisan migrate

php artisan migrate

Step 2: Define routes, models, and controllers.

To generate a model and controller, hit the following commands.

php artisan make:model Grocery
php artisan make:controller GroceryController

The next step is to define the routes. Then, finally, we must add the routes in the routes  >>  web.php file.

// web.php

Route::view('/grocery', 'grocery');
Route::post('/grocery/post', 'GroceryController@store');

We have not created any view files. So let us do that. First, we must create this file inside resources  >>  views  >>  grocery.blade.php.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
 <head>
   <meta charset="utf-8"/>
   <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
   <meta name="viewport" content="width=device-width, initial-scale=1"/>
   <title>Grocery Store</title>
   <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
 </head>
 <body>
   Grocery App
 </body>
</html>

Go to the cmd and start the development server.

php artisan serve

Navigate to http://localhost:8000/grocery. You can see our grocery page in the browser.

Step 3: Create a bootstrap form.

In the grocery.blade.php file, write the following bootstrap code.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
 <head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Grocery Store</title>  
 </head>
 <body>
  <div class="container">
   <form id="myForm">
     <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name">
     </div>
     <div class="form-group">
      <label for="type">Type:</label>
      <input type="text" class="form-control" id="type">
     </div>
     <div class="form-group">
      <label for="price">Price:</label>
      <input type="text" class="form-control" id="price">
     </div>
    <button class="btn btn-primary">Submit</button>
 </form>
 </div>
 </body>
</html>

Step 4: Setup Bootstrap CSS and jQuery in Laravel 10

By default, Laravel 10 utilizes Vite to bundle your assets. During local development, st build times and near instantaneous Hot Module Replacement (HMR). In all new Laravel applications, including those using our starter kits, you will find a vite.config.js file that loads our lightweight Laravel Vite plugin, making Vite a joy to use with Laravel applications.

The next step is installing the Laravel UI Package using the below command.

composer require laravel/ui --dev

Now add Bootstrap with auth scaffolding.

php artisan ui bootstrap --auth

Add the jQuery library inside the package.json file in your root project folder.

 "devDependencies": {
   "@popperjs/core": "^2.11.6",
   "axios": "^1.1.2",
   "bootstrap": "^5.2.3",
   "laravel-vite-plugin": "^0.7.5",
   "sass": "^1.56.1",
   "vite": "^4.0.0",
   "jquery": "3.7.0"
 }

Now, run the below commands one by one.

npm install

npm run build

Write the code below inside the resources >> js >> app.js fide.

import './bootstrap';

import jQuery from "jquery";

window.$ = jQuery;

Update your grocery.blade.php file.

 <head>
   <meta charset="utf-8"/>
   <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
   <meta name="viewport" content="width=device-width, initial-scale=1"/>
   <title>Grocery Store</title>
   <!-- Scripts -->
   @vite(['resources/sass/app.scss', 'resources/js/app.js'])
 </head>

Step 5: Set up an Ajax request for Laravel.

First, we need to define the CSRF token in our meta tag. In previous cases, we described the field called “{{ csrf_field() }},” but in our Ajax case, we have defined it in the meta tag.

When we set up an Ajax request, we also need to set up a header for our csrf token.

Add jQuery.ajax() function in that click event to submit the request to the server with all three inputs data.

Write the below code before the </body> tag inside the grocery.blade.php file.

<script>
 document.addEventListener('DOMContentLoaded', function () {
  $(document).ready(function(){
    $('#ajaxSubmit').click(function(e){
      e.preventDefault();
      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
      });
     
      $.ajax({
        url: "{{ url('/grocery/post') }}",
        type: 'POST',
        data: {
          name: $('#name').val(),
          type: $('#type').val(),
          price: $('#price').val()
         },
       success: function(result){
         console.log(result);
       }});
     });
   });
 }, false);
 </script>

$.ajax() function contains an object of parameters. It contains a URL to send the request, a method property to check which HTTP request method is used, and a data object that contains all the form data.

The success and error function is there. If our request sends successfully, we can catch the returned data in the success function, and if it throws an error, we can see it in the error function.

Step 6: Write the store function in the Controller file

Switch to the GroceryController.php file and add the following code.

// GroceryController.php

use App\Models\Grocery;

 public function store(Request $request)
 {
   $grocery = new Grocery();
   $grocery->name = $request->name;
   $grocery->type = $request->type;
   $grocery->price = $request->price;

   $grocery->save();
   return response()->json(['success'=>'Data is successfully added']);
 }

We need to display the message that we have successfully added the data.

Go to the app >> Providers >> RouteServiceProvider.php file and add the namespace like this:

Route::middleware('web')
  ->namespace('App\Http\Controllers')
  ->group(base_path('routes/web.php'));

Step 7: Wrapping up the blade file

Our final grocery.blade.php file looks like this:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
 <head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Grocery Store</title>
  @vite(['resources/sass/app.scss', 'resources/js/app.js'])
 </head>
 <body>
  <div class="container">
  <div class="alert alert-success" style="display:none"></div>
  <form id="myForm"> 
   <div class="form-group"> 
     <label for="name">Name:</label> <input type="text" class="form-control" id="name"> 
   </div> 
   <div class="form-group"> 
     <label for="type">Type:</label> 
     <input type="text" class="form-control" id="type">
   </div> 
   <div class="form-group"> 
     <label for="price">Price:</label> 
     <input type="text" class="form-control" id="price"> 
   </div>
   <div class="form-group"> 
     <button class="btn btn-primary" id="ajaxSubmit">Submit</button> 
   </div> 
  </form>
 </div>
 <script>
  document.addEventListener('DOMContentLoaded', function () {
    $(document).ready(function(){
      $('#ajaxSubmit').click(function(e){
        e.preventDefault();
        $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
        });
        $.ajax({
          url: "grocery/post",
          type: "POST",
          data: {
            name: $('#name').val(),
            type: $('#type').val(),
            price: $('#price').val()
          },
          dataType: 'json',
            success: function(result){
              $('.alert').show();
              $('.alert').html(result.success);
            }});
         });
      });
    }, false);
 </script>
 </body>
</html>

So, I have displayed the message that data has been successfully added here on success.

We successfully posted the data into the database using AJAX in Laravel 10.

Laravel 10 Ajax - How to Use Ajax in Laravel

That’s it.

30 thoughts on “How to Use Ajax in Laravel 10”

  1. Thank you. Yours is the 5th ajax-laravel intro tute I’ve tried and the first one that actually worked. Much appreciated.

    Reply
  2. Hi, everyone. Any help is appreciated. I run laravel on Xampp and cannot save to the database.
    i have this error.

    Failed to load resource: the server responded with a status of 500 (Internal Server Error)

    Reply
    • You have to include your model in the GroceryController.php via namespace.

      > namespace App\Http\Controllers;
      >
      > use Illuminate\Http\Request;
      > use App\Grocery;
      >
      >class GroceryController extends Controller {

      Reply
  3. How can i directly display the data after i store it in the database? For now i have to refresh the page and then it shows my new entry. But i thougt ajax do it directly?? how can i do it 🙁

    Reply
  4. You need to also add use App\Grocery to GroceryController.php so that you can access the database model from the controller, otherwise you’ll get a 500 error.

    Reply
      • bro you are really a gentleman. I am very happy to read and understand your post regard on AJAX in laravel. Thank you very much. In addition what I need your help is, please teach me how to Multi-step form in laravel and use AJAX for saving the form data in Database.Please give me the resource regarding to my request if there!

        Reply
  5. I am developing application using plain PHP , Javascript and Ajax . I don’t use jquery
    I do not understand hoe Laravel can help me ?? Seems to be too many layers for nothing

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.