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

Php Laravel password hash and check

How to create hash password in laravel 8 ?

January 26, 2022January 26, 2022

Laravel provides robust security features and one of them are hash password which is not decryptable. For hashing the password laravel use secure Bcrypt and Argon2 hashing for storing user passwords. Password encrypted with Bcrypt can not be decrypt since it uses key to generate the hashed string and irreversible…

Read More
Php How to Prepend or Append File Content in Laravel

How to Prepend or Append File Content in Laravel ?

May 29, 2022May 29, 2022

In our last article I showed you to create file and this article will cover to Prepend or Append File Content in Laravel application. To perform the file system based operations like create, replace, prepend or append File Content file in laravel, we use File class or Storage class in…

Read More
Php Custom helper function laravel

How to Create Custom Helper Functions in Laravel ?

December 21, 2021November 8, 2023

Sometimes in our application we want to create custom helper functions in laravel to use in our application, Laravel has so many helpers functions to work with strings, URL, email, array, debugging etc. so in this article i will show you to use custom helper functions in our Laravel application….

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

  • 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 Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version