AppDividend
Latest Code Tutorials

Laravel AJAX Tutorial Example

Laravel 5.5 AJAX

17,431

Get real time updates directly on you device, subscribe now.

Laravel AJAX Tutorial Example topic. For this session, we will use Laravel 5.5. From the last three years, Laravel is PHP’s dominant framework. So many web applications are building in Laravel right now. Laravel Ecosystem is revolutionizing the PHP Web application. Until now, we have inserted the data with a page refresh. But now we will see how we can use AJAX request to enter the data into the database and retrieve it. If you are new to Laravel then check out my Laravel Tutorial Example From Scratch.

Introduction

AJAX is the way to communicate between client and server without page refresh. It is the technique to pass the data from one server to another server without having any interruption. Full form of AJAX is Asynchronous Javascript and XML. In the regular form, we define the post route in action but, in this case, we describe the action in Javascript and let javascript code handle the rest.

Difference between Normal and AJAX request.

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

While in AJAX request, a client request to the server, the server responds with the data and not the whole page. So that is the main difference between regular and ajax request. The server returns the data either in JSON format or XML format. Nowadays JSON becomes more and more popular.

Laravel 5.5 AJAX

Laravel AJAX Tutorial

We will use AJAX in Laravel 5.5. First, we will create a simple form using bootstrap. Then using jQuery, 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 the Laravel.

Step 1: Install and configure the Laravel.

You can install the Laravel with the following command.

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

After installing the Laravel, we need to configure the database. You can set your database credentials in the .env file. We are building simple Grocery Application, where the user can add the item. So first we need to develop the schema for that. For generating 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, model and controllers.

To generate model and controller, hit the following commands.

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

Next step is to define the routes. We need to add the routes in the routes  >>  web.php file.

// web.php

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

Till now, we have not created any view file. So let us do that. We need to 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>

Okay, now add a jQuery in the grocery.blade.php file. Remeber that you need 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: Setup an Ajax request for Laravel.

First, we need to define the CSRF token in our meta tag. In previous cases, we describe the field called “{{ csrf_field() }},” but in our ajax case, we have defined in the meta tag. When we set up an ajax request, we also need to setup header for our csrf token. When we post the data to the server, it needs to contain 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.

Related Posts
1 of 37

Now, Add the jQuery.ajax() function in that click event to submit the request to the server with all the 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 URL to send the request, method property to check which HTTP request method is used, a data object that contains all the form data. The success and error function is there. If our request sends successfully then, we can catch the returned data in the success function, and if it throws an error, then we can catch the error 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']);
 }

Now, 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, here on success, I have displayed the message that data has been successfully added.

Finally, Our Laravel AJAX Tutorial with an example is over.

 

3 Comments
  1. ryan says

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

  2. Chris says

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

  3. tyuyutu says

    utuy

Leave A Reply

Your email address will not be published.

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