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 How to use join in Laravel Eloquent

How to use join in Laravel eloquent query with example

February 1, 2022November 5, 2023

In this article we will learn to use join in laravel eloquent and query builder. Laravel itself provide inbuilt method to join the table like in MySQL or SQL based database we can do join multiple tables using join function. laravel eloquent Join method by default use inner join. For…

Read More
Uncategorized rollback specific migration in laravel

How to rollback specific migration in laravel ?

March 6, 2022February 8, 2024

In this article we will learn rollback specific migration in laravel, in our recent article i wrote about creating migration in laravel and sometimes after creating migration we want to rollback specific migration laravel so in this article i will show you to rollback a specific migration in laravel. Laravel…

Read More
Php Laravel where or condition with example

How to use laravel where or condition with example ?

January 15, 2022February 19, 2022

Laravel eloquent provides multiple ways to build the query one the of the feature of laravel eloquent is creating dynamic query based on condition or complicated queries.In this article i will show you to build where or condition in laravel with example. I will show you multiple example to create…

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