Laravel 8 Ajax Post Request Tutorial

Share this Article
Reading Time: 6 minutes
54 Views

In web application, submitting form data is very common. So here inside this article we will see Laravel 8 Ajax Post Request. This tutorial is in very easy steps.

Tutorial guides to submit form data using Ajax Post request in Laravel 8. We will create few files like few routes, a view file and some ajax handing methods to controller to complete this basic task.

Also we will implement Client side form validation using jquery validate plugin. Also if you want to implement server side validation, then also we can use Laravel Form validation.

Let’s get started about the Laravel 8 Ajax Post Tutorial.


Installation of Laravel 8 Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Click here to Install Composer ? Here is the complete command to create a laravel project-

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

After following these steps we can install a Laravel 8 application into system. To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel 8 already installed at system.


Create Application Routes

Open file web.php from /routes folder. Inside this file we will some routes for processing ajax request. One route is GET request type to render layout and second will be POST request to submit form data.

//import controller file
use App\Http\Controllers\AjaxController;

Route::get('add-post', [AjaxController::class, 'myPost']);
Route::post('submit-post', [AjaxController::class, 'submitPost'])->name('postSubmit');

Now, we need to create AjaxController file.


Create Controller File

Open project into terminal and type this command to create Controller file.

$ php artisan make:controller AjaxController

This command will creates a file i.e AjaxController.php at /app/Http/Controllers folder. Open this file and paste the give code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
// If work with model to save data to database
// Load model here like
// use App\Models\Post;

class AjaxController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function myPost()
    {
        return view('my-post');
    }
     
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function submitPost(Request $request)
    {
        // We are collecting all data submitting via Ajax
        $input = $request->all();
      
        /*
          $post = new Post;
          $post->name = $input['name'];
          $post->description = $input['description'];
          $post->status = $input['status'];
          $post->save();
        */
     	
        // Sending json response to client
        return response()->json([
            "status" => true,
            "data" => $input
        ]);
    }
}

Inside this above code, we have added a method which is processing ajax data. Also you can see in the comment section we have used Model concept and saved data into method as well.

Let’s create a blade file to render layout.


Create Blade Template

Go to project’s /resources/views folder, inside this create a file called my-post.blade.php. Open up the file and paste the given code.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Laravel 8 Ajax Post Request Tutorial - Online Web Tutor</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <style>
        #frm-create-post label.error{
            color:red;
        }
    </style>
</head>

<body>

    <div class="container" style="margin-top: 50px;">
        <h4 style="text-align: center;">Laravel 8 Ajax Post Request Tutorial - Online Web Tutor</h4>
        <form action="javascript:void(0)" id="frm-create-post" method="post">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" required id="name" name="name" placeholder="Enter name">
            </div>
            <div class="form-group">
                <label for="description">Description:</label>
                <textarea class="form-control" id="description" required name="description"
                    placeholder="Enter description"></textarea>
            </div>
            <div class="form-group">
                <label for="status">Status:</label>
                <select class="form-control" id="status" name="status">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>

            <button type="submit" class="btn btn-primary" id="submit-post">Submit</button>
        </form>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>

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

    $("#frm-create-post").validate({

        submitHandler: function() {

            var name = $("#name").val();
            var description = $("#description").val();
            var status = $("#status").val();

            // processing ajax request    
            $.ajax({
                url: "{{ route('postSubmit') }}",
                type: 'POST',
                dataType: "json",
                data: {
                    name: name,
                    description: description,
                    status: status
                },
                success: function(data) {
                    // log response into console
                    console.log(data);
                }
            });
        }
    });
    </script>
</body>

</html>

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

Open up the URL – http://localhost:8000/add-post

With Client side validation – jQuery Validate

Submitting Data and getting response to Console

We hope this article helped you to learn about Laravel 8 Ajax Post Request Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on Laravel 8 Articles here

Leave a Comment