Submitting an Ajax form in Laravel

0
1442

Let’s create a form without reloading the page on the Laravel framework using ajax technology. First, let’s write the routes in web.php

// New page with form – output
Route::get(‘/feedback’, array(
‘as’ => ‘site.index.feedback’,
‘uses’ => ‘IndexController@feedback’
));

// Ajax controller route

Route::post(‘/feedback’, ‘AjaxController@store’);

Let’s create a view (template with layout)

/resources/views/site/index/feedback.blade.php with form

<form id="dismissal-form" method="POST" action="{{ $url }}">
    {{ csrf_field() }}
    <div class="form-container">
        <h3 class="form-header">Dear Colleague!</h3>
        <div class="form-input-container">
            <input name="fio" class="form-text-input" type="text" placeholder="Full name (optional)">
            <input name="position" class="form-text-input" type="text" placeholder="Job title">
            <input name="experience" class="form-text-input" type="text" placeholder="Work experience in the company">
        </div>
    </div>
    <input type="button" id="dismissal-form-btn" name="submit" value="Send" class="form-submit-button">
</form>

and connect the js script there to process the form

<script src="js/script_form.js"></script>

File contents js/script_form.js

$(document).ready(function($) {

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $("#dismissal-form-btn").click(
        function(e){
            e.preventDefault();
            $.ajax({
                url:     "/feedback", //url страницы (action_ajax_form.php)
                type:     "POST", //sending method
                dataType: "html", //data format
                data: $("#dismissal-form").serialize(),  // Searilize the object
                success: function(response) { //Data sent successfully
                    $(".form-pop-up-text .form-lowertext").html("Thank you for your answers and for your work in our company.")
                    $(".form-pop-up-text .form-lowertext1").html("We wish you success in your new place!")
                    $("#pop-up-btn").addClass("success");
                    $(".form-pop-up").show();
                    $(".form-pop-up-text").show();
                    console.log(response);
                },
                error: function(response) { // Data not sent
                    $(".form-pop-up-text .form-lowertext").html("An error has occurred")
                    $(".form-pop-up-text .form-lowertext1").html("Try again")
                    $(".form-pop-up").show();
                    $(".form-pop-up-text").show();
                    console.log(response);
                }
            });
        }
    );
    $(".pop-up-btn").click(
        function (){
            if (document.getElementById("pop-up-btn").classList.contains("success")) {
                document.location.href = "https://ostrov-chistoty.by";
            }
            else{
                $(".form-pop-up").hide();
                $(".form-pop-up-text").hide();
            }
        }

    )
});

In the controllers catalog/app/Http/Controllers/ let’s create a new controller AjaxController.php

Inside the controller we create a method for submitting the form:

public function store(Request $request)
{
    // email from the site admin settings - or enter strictly $settings = "info.site.com";
    $settings = $this->getSettings('SettingsSite', 'emails');

    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $title = ($_POST["fio"] == "" ? "Anonymously" : $_POST["fio"]) . " - " . $_POST["position"] . " - experience" . $_POST["experience"];

    $text = $title . "<br>";
    $text .= "Text ... Full name: ".$_POST["fio"];

    mail($settings['recipient_form'], $title, $text, $headers);
    $response = array(
        'status' => 'success',
        'msg' => $request->message,
    );
    return response()->json($response);
}

In the controller/app/Http/Controllers/IndexController.php add a template rendering method:

public function feedback() {
    return view('site.index.feedback', array(
        'url'   => $_SERVER['REQUEST_URI']
    ));
}

Having done everything according to the instructions, you can create any form in Laravel without reloading to ajax.

LEAVE A REPLY

Please enter your comment!
Please enter your name here