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 make a component in laravel 10

How to create component in Laravel 10 ?

March 23, 2023March 16, 2024

In this tutorial i will show you simple html based component in Laravel 10 using blade. Creating reusable components is a fundamental aspect of modern web development, as it allows developers to simplify code and improve efficiency. Laravel 10, one of the most popular PHP frameworks, comes with a robust…

Read More
Php How to Check folder exist and Create a Nested Folder in Laravel

How to Check folder exist and Create Nested Folder in Laravel ?

May 24, 2022May 26, 2022

This article will guide you to Check folder exist and Create Nested Folder in Laravel. To perform the file system based operations like Check folder exist and Create a Nested Folder. we use File class in laravel. Laravel provides inbuilt library to access the file system and we can do…

Read More
Php Use Soft Delete to Temporary (Trash) Delete the Records in Laravel

Use Soft Delete to Temporary (Trash) Delete the Records in Laravel 9 ?

June 14, 2022June 14, 2022

Soft delete in laravel is use to hide the record from users by keeping the data in the database. In laravel we use Soft Delete to Temporary (Trash) Delete the Records. There is many purpose of soft delete like deleting the user for admin but keep all the information in…

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

  • 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

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version