Laravel AJAX Tutorial and MySQL Example

Today, We want to share with you Laravel Ajax: How to Use Ajax In Laravel With Example.In this post we will show you Simple Ajax request example with JQuery and PHP., hear for how to fetch data from database in php using ajax with example we will give you demo and example for implement.In this post, we will learn about Beginner’s Guide to Ajax Development with PHP with an example.

How to use AJAX in Laravel with Example

There are the Following The simple About ajax in laravel Full Information With Example and source code.

As I will cover this Post with live Working example to develop Working with jquery, PHP and MySQL, so the Introduction to Ajax for PHP Web Applications is used for this example is following below.

Step:1 Create a New Laravel Project

create a simple HTML form using bootstrap and send the data using jquery AJAX in Laravel Project

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

simple you can here update the config .env file for our database

php artisan make:model Product -mcr

generated a migration file

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

migrate the table in Database

php artisan migrate

Step:2 Now config route for our application.

routes->web.php

Route::view('/product', 'product');
Route::post('/product/post', '[email protected]');

resources -> views -> product.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>product</title>
        
    </head>
    <body>
      AJAX product App
    </body>
</html>

run the server using this bellow this command.

php artisan serve

product.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>product</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin=anonymous>
  </head>
  <body>
   <div >
     <form id="myproduct">
      <div >
       <label for="name">Name:</label>
       <input type=text id="name">
      </div>
      <div >
       <label for="pcode">pcode:</label>
       <input type=text id="product_desc">
      </div>
      <div >
        <label for="product_desc">product_desc:</label>
        <input type=text id="pcode">
       </div>
      <button >Submit</button>
     </form>
   </div>
<script src=//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.

add CSRF token in the meta tag

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

Add the jQuery.ajax() function

<script src=//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('/product/post') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     type: jQuery('#pcode').val(),
                     desc: jQuery('#product_desc').val()
                  },
                  success: function(result){
                     console.log(result);
                  }});
               });
            });
</script>

Step:5 Store data By AJAX request

ProductController.php

 public function store(Request $request)
 {
        $product = new product();
        $product->name = $request->name;
        $product->type = $request->pcode;
        $product->desc = $request->product_desc;

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

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about ajax in laravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Remove “public/index.php” from URL in Laravel
  2.   Laravel Return Ajax JSON Response Example
  3.   Laravel 5/6/7 CRUD Operations Example Step By Step
  4.   Laravel 6 Ajax post data Example
  5.   PHP Get Folder Path From File Path Examples
  6.   Laravel 6 JQuery Ajax Post Request Example
  7.   how to insert data using ajax in laravel with datatables?
  8.   jQuery Ajax Get JSON in Laravel Example
  9.   Laravel 6 JQuery Ajax Post Request Example
  10.   Jquery simple rating system with star