Convert POST request into AJAX, Javascript – Laravel
Suppose you have a form in your Laravel project that 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 render all the HTML in the browser again. So you need to convert this POST request into an AJAX request to prevent the page from reloading.
I am using a form with a text field and an input type file so you can know how to send an 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 the 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 have been added with each line for an explanation. Now we need to create a route in our web.php file inside the routes folder in Laravel 9.
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 the text field in the users table. You can find the sample database in the attachments below.
Then we are storing the image in a 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. That’s how you can convert a POST request into an AJAX request in Laravel.
[wpdm_package id=’951′]