How to use AJAX in Laravel with Example

Generic placeholder image
Brijpal Sharma
laravel ajax  

Date:-September 15th, 2018 , Posted On:- Web Development


How to use AJAX in Laravel with Example is today topic. In this topic, we learn how to work with data using AJAX in Laravel

AJAX is the technology which is known for communicating between servers and clients with loading page. AJAX pass the data from the client side to serve without any interruption. full form of AJAX is AJAX (Asynchronous Javascript and XML)

Different between AJAX and Normal Request

We know that AJAX Pass data without page refresh and another side normal request respond with full reload page. that is the main difference between normal and AJAX request. AJAX request return data either in XML format or JSON format. So Nowadays JSON becomes popular.

To learn AJAX  in Laravel request we will create a simple form using bootstrap and send the data using AJAX and store on the database.

Step:1 Create a New Laravel Project

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

After creating a new Laravel project, first, we need to configure the database so config .env file for our database. After that, we are going to create a model, Controller, and migration table using this following command.

php artisan make:model Form -mcr

Using this command it generates a model, controller, and migration files

  • Form.php (Model)
  • FormController.php (Controller)
  • create_forms_table.php (Migration)

So it has generated a migration file. Add some column name for the form.

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

Now, migrate the table using this flowing this command.

php artisan migrate

Step:2 Now config route for our application.

We need to add the routes in routes->web.php

Route::view('/form', 'form');
Route::post('/form/post', 'FormController@store');

Now create a view page for our form resources -> views  -> form.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>Form</title>
        
    </head>
    <body>
      AJAX Form App
    </body>
</html>

We have a page for form now you run the server using this flowing this command.

php artisan serve

After that you can Navigate to http://localhost:8000/form You can see our form page in the browser.

Here, we are using bootstrap for the style. so using bootstrap create a form.

Add new code in form.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>Form</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </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="email">email:</label>
              <input type="text" class="form-control" id="address">
            </div>
            <div class="form-group">
               <label for="address">address:</label>
               <input type="email" class="form-control" id="email">
             </div>
            <button class="btn btn-primary">Submit</button>
          </form>
      </div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    </body>
</html>

 

Step:4 Create an Ajax request for Laravel.

first, we need to add CSRF token in the meta tag. normally we use {{ csrf_field() }}, but in AJAX we use token in the meta tag. When we post the form data to the server, it needs to contain CSRF token in form page.

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

Ok, when the user clicks on submit form this function will call, but nothing will be happening.

Now, Add the jQuery.ajax() function on click event to submit the request to the server with all the 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('#email').val(),
                     price: jQuery('#address').val()
                  },
                  success: function(result){
                     console.log(result);
                  }});
               });
            });
</script>

In jQuery.ajax() function has an object of parameters and also added URL to send the request, method property to check which HTTP request method is used here, and the data object that added all the form data. The error and success function is there. If our request sent successfully then, success function call either error.

Step:5 Store data By AJAX request

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

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

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

Now, run your application and see the result, so here we completed How to use AJAX in Laravel with Example tutorial.

 


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

0 comments

You must be logged in to post a comment.