Usage of Laravel Ajax

In this article I want to share some details about usage of ajax which is last version of Laravel. In this article these are the things that we are going to learn.

  • Using Npm
  • Using Laravel Mix Asset Manager
  • Launching Laravel with Artisan
  • Generating Controls with Artisan
  • Laravel CSRF Token

Step 0 - Launching Laravel

First of all to launch the Laravel use this command.

php artisan serve

You can start your test by entering to this addres http://127.0.0.1:8000 or http://localhost:8000

Step 1 - Making the Necessary NPM Settings

If you just set the Laravel and if you didn't upload the packages with NPM let's start with this. Let's upload the packgaes with this command

npm install

Since we'll be using jquery for ajax operations later, we'll load it with npm in jquery in this way;

npm i jquery

Now we are ready to use Mix Asset Manager of Laravel.  Actually what it does, program uses the webpack to send our files from beneath the resources file to under the public file certain operations. When laravel setted up, js and sass files are automatically established you dont need to do anything extra. All you need to do is watching the changes by running this command.

npm run watch

That's all we do with NPM, now on when someone or us make changes to our file which is under the resources/js and resources/sass it will be detected automatically and it will be extracted automatically beneath the public.

Step 2 - Adding Asset files to views

For this operation we are going to use mix() function. Add this things to a suitable place in the <head> tag of your layout blade template that you created;

<head>
    ..
    <script src="{{ mix('js/app.js') }}"></script>
    <link rel="stylesheet" type="text/css" href="{{ mix('css/app.css') }}">
    ..
</head>

Step 3 - Generating Ajax Controller File

To do this we just need to run the artisan command.

php artisan make:controller AjaxController

It creates a php file which name is AjaxController.php beneath the app/Http/Controllers.php To edit this open and define a public method like follows:

public function index()
{
    return response()->json([
      'name'    => 'PhpExample',
      'surname' => 'Best Site For Developers'
    ], 200);
}

To use the controller we need to add them to router. Open the routes/web.php file and append this:

Route::post('/ajax', '[email protected]')->name('ajax');

Now we have a route for our ajax operations and we are ready to use.

Step 4 - Let's Fulfill Ajax Request

We open our resources/js/app.js file and we include our jquery library then we send a request. But before that url that we are going to send a request we need to write in the head tags of our layout page. Also we need to send token in requests. We locate this two things where we applied in Step 2.

<script>
    let ajax_url = "{{ route('ajax') }}",
        token    = "{{ csrf_token() }}";
</script>

Now let's open app.js file and write these codes

import $ from "jquery"

$(function () {
    
    $.post(ajax_url, {_token: token}, function(response){
        console.log(response);
    }, 'json');
    
});

As a result it will return name-surname information as an object that we sent in the controller file.So yes, we achieved to use ajax successfully.

Step 5 - Accessing the datas sent in the Ajax request

For this, let's modify our code in the next step like this;

let data = {
    _token: token,
    name: "PhpExample",
    surname: "Best Site For Developers",
    web: "http://phpexample.net"
}
$.post(ajax_url, data, function(response){
    console.log(response);
}, 'json');

We need to use Request class in our Ajaxcontroller file. So let's change as follows:

public function index(Request $request)
{
    $datas = $request->all(); // Receives all posts in a string
    
    $web = $request->input('web'); // Receives data sent with the web name

    return response()->json([
        'name'    => 'PhpExample',
        'surname' => 'Best Site For Developers'
    ], 200);
}

Of course, to use the Request class we need to state this under the namespace:

use Illuminate\Support\Facades\DB;

Step 6 - Taking Datas from Database

Actually it is not a compulsory step but if we wanted to take data from database return in the ajax request , we need to our .env file and fill the these part according to us.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=phpexample
DB_USERNAME=root
DB_PASSWORD=root

Now we can make a usage like this in our AjaxController file.

public function index()
{
    $users = DB::table('users')->limit(20)->get();
    return response()->json($users, 200);
}

Of course for this we need to add this definition after the namespace.

use Illuminate\Support\Facades\DB;

That's all, enjoyable coding :)
 

Comments

There are no comments, make the firs comment