How to Submit form laravel using ajax | websolutioncode.com
How to Submit form laravel using ajax | websolutioncode.com

How to Submit form laravel using ajax

Building a contact form with Laravel and integrating AJAX for seamless form submissions can greatly enhance the user experience on your website. In this tutorial, we’ll walk through the process of creating a Submit form laravel using ajax, making it more dynamic and responsive.

Explore the integration of AJAX in Laravel to enhance your web forms. This comprehensive tutorial provides practical code examples and easy-to-follow steps, ensuring a smooth learning experience for creating dynamic and responsive contact forms with the ability to Submit form laravel using ajax seamlessly.

Prerequisites:

Before we begin, make sure you have the following prerequisites installed on your system:

  1. Laravel installed (if not, you can follow the official Laravel installation guide).
  2. Basic knowledge of Laravel and PHP.
  3. Understanding of HTML, CSS, and JavaScript.

Step 1: Set Up a Laravel Project

If you haven’t already, create a new Laravel project using the following command:

composer create-project --prefer-dist laravel/laravel contact-form-ajax

Navigate to the project folder:

cd contact-form-ajax

Step 2: Create a Contact Controller

Generate a controller to handle the contact form:

php artisan make:controller ContactController

Open the newly created controller (app/Http/Controllers/ContactController.php) and add the following code:

php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index()
    {
        return view('contact');
    }

       
    public function savecontact(Request $request)
{
  
        $message = [];
        $valid = [

            'name' => 'required|max:100',
            'email' => 'required|email|max:100',
            'phone' => 'required|max:100',
            'subject' => 'required|max:100',
            'message' => 'required|max:1000',
        ];

        $valid_name = [
            'name' => 'Category title',
            'email' => 'Category Status',
            'phone' => 'Category Image',
            'subject' => 'Category Image',
            'message' => 'Category Image',

        ];

        $v = \Validator::make($request->all(), $valid, $message);
        $v->setAttributeNames($valid_name);

        if ($v->fails()) {
            return redirect()->back()->withErrors($v->errors())->withInput();
        } else {
            
            $category = new contact;
            $category->name = $request->get('name');
            $category->email = $request->get('email');
            $category->phone = $request->get('phone');
            $category->subject = $request->get('subject');
            $category->message = $request->get('message');
            $category->save();
            // return redirect()->back()->with(['success_msg' => 'Query Saved successfully']);
      return response()->json(['success_msg' => 'Query Saved successfully']);

}
}
}

Step 3: Create a Contact Form View

Create a new blade file for the contact form (resources/views/contact.blade.php). Add the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form with AJAX</title>
</head>
<body>

                            <form id="contactForm" class="mf_form_validate ajax_submit" action="{{url('/submit-form')}}" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input type="text" name="name" class="form-control form-control-custom" placeholder="Name">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input type="email" name="email" class="form-control form-control-custom" placeholder="Email">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input type="text" name="phone" class="form-control form-control-custom" placeholder="Phone No.">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input type="text" name="subject" class="form-control form-control-custom" placeholder="Subject">
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <textarea class="form-control form-control-custom" rows="4" name="message" placeholder="Write Something.."></textarea>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <button type="submit" class="btn-first btn-border">Submit</button>
                                </div>
                                <div class="col-12">
                                    <div class="server_response w-100"></div>
                                </div>
                            </div>
                        </form>


    <div id="response"></div>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
    $(document).ready(function () {
        // Intercept form submission
        $('#contactForm').submit(function (e) {
            e.preventDefault(); // Prevent the default form submission

            // Get form data
            var formData = new FormData($(this)[0]);

            // Make an AJAX request
            $.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    // Handle the success response, update UI or show a message
                    $('.server_response').html(response.success_msg);
                        $('#contactForm')[0].reset();

                },
                error: function (xhr, status, error) {
                    // Handle the error, display an error message
                    console.error(xhr.responseText);
                }
            });
        });
    });
</script>


</body>
</html>

Step 4: Define Routes

Open the routes/web.php file and add the following routes:

use App\Http\Controllers\ContactController;

Route::get('/contact', [ContactController::class, 'index']);
Route::post('/submit-form', [ContactController::class, 'submitForm']);

Step 5: Run the Application

Run the development server:

php artisan serve

Visit http://localhost:8000/contact in your browser to access the contact form. Fill in the details and click the submit button. The form data will be processed asynchronously using AJAX.

Conclusion:

Congratulations! You have successfully implemented a contact form with Laravel and AJAX. This tutorial covers the essential steps to create a dynamic and responsive form, providing a seamless user experience. Feel free to customize and expand upon this example for your specific needs.

This Post Has One Comment

  1. Long Hairstyles

    Thank you for your articles. They are very helpful to me. Can you help me with something?

Leave a Reply