Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel ajax form with example

Submit form using jQuery in Laravel

Aman Jain, November 18, 2021November 18, 2021

jQuery is most popular library to handle the client side events like form submit, click, change etc. In this article we will learn to submit the form using jQuery Ajax method. Ajax is mostly used when we do not want to reload the page and real time interaction. In this example we will learn Ajax form validation and form submit of post.

Let’s begin the tutorial of submit form using jquery in simple steps:

Step 1: Create Laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2: Create controller

Now, create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Post;
use Illuminate\Support\Facades\Storage;

class PostController extends Controller
{

     /**
     * Show the form to create a new blog post.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',   // required  validation
            'description' => 'required', 
            'picture' => ['required','image','mimes:jpeg,png,jpg,gif,svg','max:2048'],
        ]); // create the validations
        
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            return response()->json($validator->errors(),422);
            // validation failed redirect back to form

        }
        else
        {
         
             //handle the form 
            $post=new Post();
            $post->title=$request->get("title");
            $post->description=$request->get("description");
            $post->picture_name=$request->file("picture")->getClientOriginalName();
            $post->picture=$request->file("picture")->store("public/profile");
            $post->save();

            // Don't forget to create symbolic link using php artisan storage:link

            $post->picture= url(Storage::url($post->picture));
            
            return response()->json(["status"=>true,"msg"=>"Post submitted successfully","post"=>$post]); 
           
        }  
    }
    
     
}

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

Next, we created a object of model Post then saved file in to storage using $request->file("picture")->store("public/profile") and create a symbolic link using php artisan storage:link.

Then, we response back with json output.

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.

<div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>Laravel 8 ajax form - Readerstacks</h3>
            <div class='alert alert-success' style='display:none' id="suc_msg"></div>
            <form method="post" id="handleAjax" action="{{url('submit-post')}}" name="postform">
              <div class="form-group">
                <label>Title</label>
                <input type="text" name="title" class="form-control" />
                @csrf
              </div>
              <div class="form-group">
                <label>Description</label>
                <textarea name="description" class=" form-control"></textarea>

              </div>
              <div class="form-group">
                <label>Picture</label>
                <input type="file" name="picture" class="form-control" />

              </div>
              <div class="form-group">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Laravel 8 ajax form </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>

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() {
      $("#handleAjax").on("submit", function(e) { //id of form 
        e.preventDefault();
        var action = $(this).attr("action"); //get submit action from form
        var method = $(this).attr("method"); // get submit method
        var form_data = new FormData($(this)[0]); // convert form into formdata 
        var form = $(this);
        $.ajax({
          url: action,
          dataType: 'json', // what to expect back from the server
          cache: false,
          contentType: false,
          processData: false,
          data: form_data,
          type: method,

          success: function(response) {
            if (response.status) {
              $(".alert-danger").remove();
              form.trigger("reset");
              $("#suc_msg").show();
              var data = `${response.msg}
                                <div>id : ${response.post.id} <br>
                                title :   ${response.post.title} <br>
                                Image : <img src='${response.post.picture}' width=100 /> <br></div>`;
              $("#suc_msg").html(data);

            }
            // display success response from the server
          },
          error: function(response) { // handle the error
            $(".alert-danger").remove();
            try {
              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>");
              }
              if (options.error) {
                options.error(response);
              }
            } catch (err) {

            }

          },

        })
      });

    });

     
  </script>

Here, we added ("#handleAjax").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.

We are also rendering the submitted post with success message you can check screenshots.

Step 5: Create routes

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

<?php

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


Route::get('/create-post',[PostController::class, 'create']);
Route::post('/submit-post',[PostController::class, 'store']);

Screenshots

  • Screenshot 2021 11 18 at 8.19.52 AM
  • Screenshot 2021 11 18 at 8.20.21 AM
  • Screenshot 2021 11 18 at 8.20.38 AM
Laravel Ajax form

Related

Uncategorized Laravel Php ajaxformlaravelphp

Post navigation

Previous post
Next post

Related Posts

Laravel array validation with example

December 15, 2021November 12, 2023

In this tutorial i will explain to use validating a array inputs using Laravel validation library. Laravel also supports to validate group of array and we can validate a array same as normal input. In our recent article Laravel form validation how to validate a form and files. In this…

Read More
Php Laravel pagination with search

How to use Laravel pagination with search ?

February 22, 2022November 19, 2023

In this tutorial we will learn pagination in Laravel. Laravel provides its own library to build the pagination html, which we can easily use in our html page using $model->links() method and $model->paginate() method to make a long list into pagination. Thus in this tutorial i will show you to…

Read More
Php How to compress and reduce image size while uploading in laravel

How to compress and reduce image size while uploading in laravel 9 ?

May 14, 2022May 15, 2022

While uploading the images in our application user can upload big size image but storing and rendering big size of image can reduce the performance of the application therefor its an important aspect to reduce the size of image without resizing it so we can keep the original size 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

  • 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
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version