Using Ajax in Laravel: Controller, View, and Route Setup
This tutorial walks through creating a Laravel controller, view, and route to handle Ajax requests, integrating jQuery on the front end, and displaying the server response, providing a practical example for backend developers to implement asynchronous interactions in a PHP application.
This article provides a step‑by‑step tutorial on using Ajax in a Laravel project that is already installed and running.
Creating the controller : Run php artisan make:controller TestController in the project root. Laravel creates app/Http/Controllers/TestController.php . Add two methods:
<code>public function index(){
return view('test');
}
public function testAjax(){
echo '请求成功了';
die;
}</code>Creating the view file : In resources/views create test.blade.php .
Route configuration : Edit routes/web.php and add the following routes:
<code>Route::get('test', [TestController::class, 'index'])->name('test.index');
Route::post('test', [TestController::class, 'testAjax'])->name('test.ajax');</code>Adding an entry link : Open resources/views/welcome.blade.php (around line 111) and insert the link:
<code><a href="{{route('test.index')}}" class="ml-1 underline">测试入口</a></code>Including jQuery : Place jquery.min.js into public/assets and reference it in the test view.
Front‑end page code (test.blade.php):
<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Ajax</title>
<script src="{{asset('assets/jquery.min.js')}}"></script>
</head>
<body>
<p class="response-message" style="color: red"></p>
<form method="post" action="{{route('test.ajax')}}">
{!! csrf_field() !!}
提交的内容:<input type="text" name="text">
<span class="submit-btn">提交</span>
</form>
<script>
$('.submit-btn').click(function(){
let url = $(this).closest('form').attr('action');
let formData = $(this).closest('form').serialize();
$.post(url, formData, function(response){
$('.response-message').text(response);
});
});
</script>
</body>
</html></code>After saving, open the test page, enter text, and click the submit button; the response from TestController@testAjax will be displayed.
Modifying the controller for JSON response : Change testAjax() to return a JSON object, e.g., return response()->json(['data'=>['text'=>'Your message']]); , and update the front‑end script to extract response.data.text and insert it into the page.
Finally, the article notes that this covers basic Ajax usage in Laravel, and readers can explore similar implementations in Vue, React, or other front‑end frameworks.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.