Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Laravel

How to Use Ajax in Laravel 11

  • 22 Jan, 2025
  • Com 23
How to Use Ajax in Laravel

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

Visual Representation of AJAX Request

The syntax of the jQuery Ajax is as follows:

jQuery.ajax( url [, settings ] )

How to Use Ajax?

To use Ajax, jQuery sends a network request to the server without a page refresh. 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, we will send a request to the server using the jQuery ajax() or post() method to store the form values in the database.

Here is the step-by-step guide:

Step 1: Install and configure Laravel.

Let’s install Laravel 11 using this command:

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

Here is our newly installed project:

Laravel 11 Starter Page

After installing Laravel, we need to configure the database.

You need to set your database credentials in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=lara11
DB_USERNAME=root
DB_PASSWORD=root

My database name is lara11; you can give any name and create it inside phpmyadmin or any mysql database.

We will build a simple Grocery application where the user can add the item.

So, first, we need to develop the schema for that.

To generate a model and migration file, use this command:

php artisan make:model Grocery -m

The above command generates two files:

  1. Grocery.php: It is a model file.
  2. create_groceries_table.php: It is a migration file.

Add the columns to the migration file like this:

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

Migrate the table into our database.

php artisan migrate

Migrating tables

Switch to your phpmyadmin, and you will find groceries and other tables.

Groceries table

Step 2: Install laravel/ui

We will use Bootstrap CSS for this tutorial, so we must install some packages.

Go to the root of our “lara11” project and type the following command to install laravel/ui:

composer require laravel/ui

Installing laravel/ui

Once the laravel/ui package has been installed, you may install the frontend scaffolding using the ui Artisan command:

php artisan ui bootstrap

Bootstrap scaffolding

Install the required dependencies using this command:

npm install

Now, compile our fresh scaffolding using these commands:

npm run dev

It will start a vite development server to track the changes in our CSS or JS files and recompile automatically!

Step 3: Define routes and controllers.

Here is a command to generate a Controller file.

php artisan make:controller GroceryController

The next step is to define the routes.

Add the routes in the routes  >>  web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GroceryController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('grocery/create', [GroceryController::class, 'create'])->name('grocery.create');
Route::post('/grocery/post', [GroceryController::class, 'store'])->name('grocery.store');

Create two empty functions called “create()” and “store()” inside GroceryController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Grocery;

class GroceryController extends Controller
{
    public function create()
    {
    }
    public function store(Request $request)
    {

    }
}

You can see that we imported the Grocery.php model inside the GroceryController.php file.

We will add the codes inside these functions later!

Step 4: Create a view file

We have not created any view files. So let us do that.

First, create a grocery.blade.php file inside the resources  >>  views folder and create a bootstrap form.

<!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>
            <br />
            <button class="btn btn-primary" id = "ajaxSubmit">Submit</button>
        </form>
    </div>
    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
    <script
        src="https://code.jquery.com/jquery-3.7.1.min.js"
        integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
        crossorigin="anonymous"></script>
</body>
</html>

To display this view file, return this view using the GroceryController’s create() method.

public function create()
{
   return view('grocery');
}

Go to the command line or terminal and start the development server.

php artisan serve

Navigate to http://localhost:8000/grocery/create:

Basic form

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.

Step 5: Creating an AJAX request

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

Here is the complete code for the grocery.blade.php file, including the jQuery.ajax() function.

<!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">
            <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>
                <br />
                <button class="btn btn-primary" id = "ajaxSubmit">Submit</button>
            </form>
        </div>
        <!-- Scripts -->
        @vite(['resources/sass/app.scss', 'resources/js/app.js'])
        <script
            src="https://code.jquery.com/jquery-3.7.1.min.js"
            integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
            crossorigin="anonymous"></script>
        <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: "{{ url('/grocery/post') }}",
                        type: 'POST',
                        data: {
                            name: $('#name').val(),
                            type: $('#type').val(),
                            price: $('#price').val()
                        },
                        success: function(result){
                            $('.alert').show();
                            $('.alert').html(result.success);
                        },
                        error: function(xhr, status, error){
                            // Handle the error here
                            console.error("Error occurred: " + status + "\nError: " + error);
                            // Optionally, you can handle different HTTP response codes differently
                            if(xhr.status === 404){
                                console.error("Not Found");
                            }
                            // Further handling or user notification
                        }
                    });
                });
            });
        }, false);
    </script>
    </body>
</html>

The $.ajax() function contains an object of parameters. It includes 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 is sent 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: Saving the data from the AJAX POST request into the database

Switch to the GroceryController.php file and complete the store() function.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Grocery;

class GroceryController extends Controller
{
    public function create()
    {
        return view('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']);
    }
}

Head to this URL: http://localhost:8000/grocery/create, and try adding groceries to the database.

If everything is correct, then you will see the success message like this:

Successfully saved the data using AJAX request

You can verify the inserted data into the groceries table in the database like this:

groceries table data

That’s it. We successfully sent an AJAX POST request to the server and saved the data into the database without refreshing the page.

Post Views: 76
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

Creating Pandas DataFrame From List of Tuples in Python
Converting Pandas DataFrame to Numpy Array

23 Comments

  1. ryan

    February 13, 2018 at 2:22 am

    really appreciate your work. keep going. it will be fine if you make next tutorial for role base authentication in laravel

    Reply
  2. Chris

    March 7, 2018 at 4:17 am

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

    Reply
  3. tyuyutu

    July 14, 2018 at 7:15 am

    utuy

    Reply
  4. sandip poudel

    August 18, 2018 at 8:30 am

    data is not being stored in database?

    Reply
    1. fazz

      September 2, 2018 at 7:24 am

      right

      Reply
  5. abolfazl

    September 8, 2018 at 7:27 pm

    thanks a lot (:

    Reply
  6. Tuan

    October 12, 2018 at 6:20 am

    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
    1. JESSE

      October 23, 2018 at 12:59 pm

      hello can you check the contents stored at storage/logs/laravel.log

      Reply
  7. crismith

    November 5, 2018 at 9:32 pm

    muchas gracias

    Reply
  8. GreateFul

    December 19, 2018 at 6:30 am

    Thanks sir 🙂

    Reply
  9. Mehdi

    January 23, 2019 at 12:31 pm

    Thank you so much sir

    Reply
  10. Darshan

    February 5, 2019 at 6:34 am

    Hiii,
    Awesome Content
    Very Use Full…

    Reply
  11. komallah

    February 21, 2019 at 6:39 am

    after the data has been submitted set values to null

    Reply
  12. Mohan

    February 23, 2019 at 12:04 am

    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
  13. Samuel

    July 2, 2019 at 11:15 am

    Ty, you help me alot.

    Reply
  14. abdo

    August 2, 2019 at 12:25 pm

    appreciated sir,thank u a lot

    Reply
  15. Gregory

    January 26, 2020 at 6:47 pm

    Thanks for your project.
    You are best developer.
    Thank you.

    Reply
  16. Mr. Zaryalai Ahmadi IT

    June 23, 2020 at 12:57 pm

    thanks to do your part!

    Reply
  17. Abdul Rehman

    October 29, 2021 at 11:57 pm

    please share web.config file as well

    Reply
  18. Gerry

    January 21, 2022 at 8:37 am

    thanks sir, it was worked to me as well

    Reply
  19. Fahimeh

    August 15, 2022 at 2:42 pm

    Thank you Krunal.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend