Hello, been a while, today we are going to look at a basic ajax request using jQuery and Laravel. This is to help new Laravel users (like myself :D) get acquainted with the framework and importance of routes.
Well, as you might already know Laravel is a popular open source PHP framework that promotes usage of clean Model-View-Controller (MVC) architecture.
We are going to look at how to make a simple ajax call, and then in the next blog post, how to make a more advanced dynamic ajax maneuvers that will involve, your database, migrations, eloquent and tinker.
REQUIREMENTS:
In order to practice this tutorial, you will need all of these;
- Apache & PHP
- Laravel 5
- An IDE, Sublime Text but Notepad will do for this.
Create a new View file test.blade.php in resources\views.
Fill it with sample html as you wish, the below sample contains a button to trigger the ajax request.
<!doctype html>
<html>
<head>
<title>Test Laravel Ajax</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
</head>
<body>
<button id="button">Test Ajax</button>
</body>
</html>
Fill it with sample html as you wish, the below sample contains a button to trigger the ajax request.
<!doctype html>
<html>
<head>
<title>Test Laravel Ajax</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
</head>
<body>
<button id="button">Test Ajax</button>
</body>
</html>
Now we'll add the jquery to perform the test within the head tag as shown below as shown below;
Route::get('test',function(){
return view('test');
});
Route::get('ajax/test', function(){
return "Hello World, from Ajax";
});
After this, we need to set a route path to open our test view and another for our Ajax request path to match that shown in the script in our routes file (app\Http\routes.php) to listen for the ajax request, a sample php below shows how it can be done;
Route::get('ajax/test', function(){
return "Hello World, from Ajax";
});
and voila!! your first simple ajax call in the Laravel environment.