Laravel Ajax: How to Use Ajax In Laravel

What is AJAX

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.

The full form of AJAX is Asynchronous Javascript and XML. In the standard form, we define the post route in action, but, in this case, we describe the action in JavaScript and let the JavaScript code handle the rest.

Difference between Normal and AJAX requests.

The client sends a request to the server, and the server responds with a particular page containing either static or dynamic data.

While in AJAX request, a client requests to the server, the server responds with the data and not the whole page. So that is the main difference between regular and ajax requests.

The server returns the data either in JSON format or XML format. Nowadays, JSON is becoming more and more popular.

Laravel 5.5 AJAX

The syntax of the jQuery ajax request is the following.

jQuery.ajax( url [, settings ] )

 The first parameter is the URL to which the request is sent.

The second parameter is the key/value pairs configuring the Ajax request. All settings are optional.

The default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.

Laravel AJAX

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

To use AJAX in Laravel, you need to import a jquery library in your view file to use ajax functions of jquery, which will be used to send and receive data using ajax from the server.

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.

So let us start this small application by installing Laravel.

Step 1: Install and configure Laravel.

You can install Laravel with the following command.

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

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

So it has generated the migration file; now define the columns in that file.

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

Now migrate the table into our database.

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 file.

<!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"/>

        <title>Grocery Store</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </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>

Add a jQuery in the grocery.blade.php file.

Remember to add the JS files just above the closing body tag. I have used CDN for jQuery. You can use your local jQuery file.

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
</script>

Step 4: 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.

When we post the data to the server, it must contain a CSRF token.

 jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
            });
          });

So, when the user clicks the submit button, this click event is called, and then first, we prevent the form to send and then set the headers for our future post request.

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

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous">
</script>
<script>
         jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/grocery/post') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     type: jQuery('#type').val(),
                     price: jQuery('#price').val()
                  },
                  success: function(result){
                     console.log(result);
                  }});
               });
            });
</script>

jQuery.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 catch it in the error function.

Step 5: Write the store function to store the data.

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

// GroceryController.php

use App\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.

<!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="_token" content="{{csrf_token()}}" />
        <title>Grocery Store</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </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>
            <button class="btn btn-primary" id="ajaxSubmit">Submit</button>
          </form>
      </div>
      <script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
      </script>
      <script>
         jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/grocery/post') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     type: jQuery('#type').val(),
                     price: jQuery('#price').val()
                  },
                  success: function(result){
                     jQuery('.alert').show();
                     jQuery('.alert').html(result.success);
                  }});
               });
            });
      </script>
    </body>
</html>

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

That’s it for ajax in Laravel.

29 thoughts on “Laravel Ajax: How to Use Ajax In Laravel”

  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.