Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to use Post Ajax Request in Laravel 8 9

How to use Post Ajax Request in Laravel 8 / 9?

Aman Jain, June 2, 2022June 2, 2022

Post Ajax request in laravel is use to communicate with server without reloading the page. Ajax requests are useful when we do not want to refresh the page and update the content of page so in that case Ajax request are very useful. Sometimes its also useful while submitting a form. for example submitting a form with email or other fields and we want to apply server side validations then we can show server side validation without loosing the current values of fields.

In this article i will show you to use Post Ajax Request in Laravel. For this purpose we will use jQuery, using jQuery we will use post method of it and send the request to the server.

We will understand this with a simple example of a form with validation and insert the data database using controller, model and views.

Laravel ajax request is almost same as other languages, only thing we need to keep in mind is csrf token in post request so add it as below

<script type="text/javascript">
      
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  //or 

   $.post("url",{
    "_token":$('meta[name="csrf-token"]').attr('content')
    },function(data) {  })
</script>

Let’s start the tutorial of use Post Ajax Request in Laravel step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

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

You can also read this to start with new project

Step 2 : Create a table and model

Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;
    
}

and migration file database/migrations/timestamp_create_articles_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

and then migrate the migration

php artisan migrate

Step 3 : Create controller

Let’s create a controller and add a methods showArticle and addArticle

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
    public function index(Request $request){
      return view('articles.article');
    }
    public function getArticles(Request $request){

        $articles = Article::orderBy("id","DESC")->limit(10)->get();
        return view('articles.article-pagination ',['articles'=>$articles]); 
     }
 
     function addArticle(Request $request){
        
        $validator = Validator::make($request->all(),[
                        'title' => "required",
                        'email' => "required|email",
                        
                    ]);
        if ($validator->fails()) 
        {
            return response()->json($validator->errors(),422);
        }
         
         //  save image and name in database
           $Article=new Article();
           $Article->title=$request->title;
           $Article->email=$request->email;
           $Article->save();
           return response()->json(["status"=>true,"message"=>"Form submitted successfully"]);
     }
}

Most important thing which is we have done here is response()->json() method to send the json for ajax request.

response()->json();

Here , we added two methods one for to show the form view(showArticle) and addArticle to handle the form submit and validation.

Next, we have added validation for title and email. Email is required and should be format of email. Then, title number should be required.

Step 3: Create blade file for view

Now it’s time to show the form and validation message to our view, so let’s create the view file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Laravel post Ajax request - Readerstacks </title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

</head>

<body>
    <div class="container">

        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2>Laravel post Ajax request - Readerstacks</h2>
            </div>
            <div class="panel-body">

            <form method="post" id="validateajax" action="{{url('add-article')}}" name="registerform">
              <div class="form-group">
                <label>Email</label>
                <input type="text" name="email" value="" class="form-control" />

                @error('email')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                @csrf
              </div>
              <div class="form-group">
                <label>title</label>
                <input type="text" name="title" value="" class="form-control" />
                
              </div>
              

              <div class="form-group">
                <button class="btn btn-primary">Submit</button>
              </div>
            </form>
            <div id="pagination_data">
                        
            </div>
                
            </div>
        </div>
    </div>
</body>
<script>
    $(function() {
      $("#validateajax").on("submit", function() {

          var action = $(this).attr("action");
          var method = $(this).attr("method");
          if (method == "post") {
            $.post(action, $(this).serialize(), function(data) {
              alert("Form submitted successfully")
                $("#validateajax").trigger("reset");
                getArticles();
            }).fail(function(response) {
              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                  $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

            });;
          }
          return false;

        });
     var getArticles=function(){
       $.get('{{url("get-articles")}}',function(data){
         $("#pagination_data").html(data);
       })
     }
     getArticles();
    });

     
  </script>
</html>

And resources/views/articles/article-pagination.blade.php

<table class="table table-striped table-dark table-bordered">
  <tr>
    <th>Sr No.</th>
    <th>Title</th>

    <th>Email</th>

    <th>Date</th>
  </tr>
  @foreach($articles as $article)
  <tr>
    <td>{{$article->id}}</td>
    <td>{{$article->title}}</td>

    <td>{{$article->email}}</td>
    <td>{{$article->created_at}}</td>
  </tr>
  @endforeach
</table>

Step 4: Add jQuery to handle the form submit

Here is the main logic to handle the form submit using jquery. In this step we will handle form submit using the query post method.

  <script>
    $(function() {
      $("#validateajax").on("submit", function() {

          var action = $(this).attr("action");
          var method = $(this).attr("method");
          if (method == "post") {
            $.post(action, $(this).serialize(), function(data) {
              alert("Form submitted successfully")
              $("#validateajax").trigger("reset");
              getArticles(); 
            }).fail(function(response) {
              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                  $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

            });;
          }
          return false;

        });
     var getArticles=function(){
       $.get('{{url("get-articles")}}',function(data){
         $("#pagination_data").html(data);
       })
     }
     getArticles();
    });

     
  </script>

Here, we added ("#validateajax").on("submit", function() {} to handle the submit event of form. Then, create a post request using $.post and also get the value of form action.

In next line we are handling the fail and success state. if the AJAX failed then it come into the fail block (Http response code 422). if the response code is 200 then it will come into success block.

getArticles function to fetch the lastest added articles from database without reload the page

You can also read Laravel Ajax pagination with search

              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                  $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

Above code we are using to show the validation message below the each field.

Step 5: Create routes

Now, open the routes/web.php and add below routes

<?php

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



Route::get('/',[ArticleController::class, 'index']);
Route::get('/get-articles',[ArticleController::class, 'getArticles']);
Route::post('/add-article',[ArticleController::class, 'addArticle']);
Ajax post request laravel
Ajax post request laravel
Screenshot 2022 06 02 at 8.58.23 AM

Related

Laravel Laravel 9 Php ajaxlaravelpost

Post navigation

Previous post
Next post

Related Posts

Php How to drop foreign key in laravel migration

How to drop foreign key in laravel migration ?

September 28, 2022March 16, 2024

Drop foreign key to existing table are easy as creating a foreign key and adding columns to it. In laravel migration we can drop foreign key in laravel migration to existing table using dropForeign method of migration class. Major difference between creating new table and updating new table is Schema::create…

Read More
Laravel Create database connection in laravel

How to make database connection in Laravel 8 ?

December 14, 2021February 22, 2024

Laravel comes with first party support for several database drivers. Laravel gives much better flexibility in terms of using the RDBMS based databases. Laravel supports MySQL, PostgreSQL, SQLite and SQL Server by default but if you want to make connection with Mongo or other database then you need to install…

Read More
Php Facebook Login or Signup in laravel 8 9

How to Implement Facebook Login or Signup in laravel 8 / 9 ?

March 19, 2022March 19, 2022

Facebook login or signup in laravel are demanding from start as it gives user to access the website in single click. Facebook is widely used social media platform therefore most of the users are on it and we can take leverage of it by providing the feature of login and…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version