How to convert a POST request into AJAX, Javascript – Laravel

Suppose you have a form in your Laravel project which when submit sends the data to the server for processing. But when the form is submitted, your browser has to refresh the whole page which means that it needs to load all the CSS, JS, and image files again and also to render all the HTML in the browser again.

This can be prevented by converting that request into AJAX using Javascript. I am using a form with a text field and an input type file so yo can know how to send image in an AJAX request.

<form method="POST" action="{{ url('/form-submit') }}" enctype="multipart/form-data" onsubmit="return onsubmitForm(this);">
    {{ csrf_field() }}

    <input type="text" name="name">
    <input type="file" name="file" accept="image/*">

    <input type="submit">
</form>

CSRF field is required in Laravel for POST requests. onsubmit event is attached to the form and it will call a Javascript function to send an AJAX request. Now we need to create that function in Javascript that will send an AJAX request to the server along with all the data in form:

<script>
    // create function in Javascript
    function onsubmitForm(form) {

        // create AJAX instance
        var ajax = new XMLHttpRequest();

        // open the request
        ajax.open("POST", form.getAttribute("action"), true);

        // listen for response from server
        ajax.onreadystatechange = function () {
            // when the request is successfull
            if (this.readyState == 4 && this.status == 200) {
                // convert the JSON response into Javascript object
                var data = JSON.parse(this.responseText);

                // show the response
                alert(data.status + " - " + data.message);
            }

            // if the request fails
            if (this.status == 500) {
                alert(this.responseText);
            }
        };

        // create form data object
        var formData = new FormData(form);

        // send the request
        ajax.send(formData);

        // prevent the form from submitting
        return false;
    }
</script>

Comments has been added with each line for explanation. Now we need to create a route in our web.php file inside routes folder in Laravel 8.

use Illuminate\Http\Request;

Route::get('/', function () {
    return view('welcome');
});

// this is the route I will make it to return JSON data
Route::post("/form-submit", function (Request $request) {

    $request->validate([
        "name" => "required",
        "file" => "required|image"
    ]);

    DB::table("users")->insert([
        "name" => $request->name
    ]);

    $request->file("file")->storeAs("/public", $request->file("file")->getClientOriginalName());

    // return redirect()->back();

    // return the response in JSON
    return response()->json([
        "status" => "success",
        "message" => "Task has been done"
    ]);
});

First we are validating that the request must have name and file fields and the file must be an image. Then we are inserting the data from text field in users table, you can find the sample database in the attachments below.

Then we are storing the image in public/storage folder. You need to run the following command in order to make this work:

php artisan storage:link

Lastly, we are sending the response back in JSON format.

Leave a Reply

Please disable your adblocker or whitelist this site!