Last Updated:

Using AJAX requests in Laravel

Hello. Very often when developing a project, we encounter sending ajax requests. In this article, we will talk about how to properly implement sending ajax requests in Laravel.

 

And so let's get started. I have Laravel 5.5.13 installed

AJAX requests in Laravel 1

To configure a database connection

Let's create a lara database. Now open the .env file, which is located in the root of our project and configure the connection to the database:

  • DB_DATABASE – specify the name of the database
  • DB_USERNAME – login to connect to the database
  • DB_PASSWORD is the password to connect to the database

In my case, the section with the database connection settings:

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=lara

DB_USERNAME=root

DB_PASSWORD=

Create a migration to Laravel

Let's create a create_articles_table migration that will create a table in the articles database with fields:

  • id – indexifier
  • title – the title of the article
  • text – text of the article
  • created_at – date of creation of the article
  • updated_at – updated article

To do this, run the following command in the console:

php artisan make:migration create_articles_table --create=articles
AJAX requests in Laravel 2

Now, in the up method of our newly created migration (database/migrations/<Doublish_date>_<id-migration>_create_articles_table.php), let's add the following code:

public function up()

{

Schema::create('articles', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('text');

$table->timestamps();

});

}

And start the migration process:

php artisan migrate

AJAX requests in Laravel 3

Excellent, migration accomplished. If we go to our database, we will see that the articles table has been created (in addition to the tables: migrations, password_resets and users).

Create a model in Laravel

Now we need to create a model to work with our articles table. To do this, run the following command in the console:

php artisan make:model Article

AJAX requests in Laravel 5

And let's add the following code to our model (app/Article.php):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model

{

protected $fillable = [

'title', 'text'

];

}

Creating a controller in Laravel

Now let's create a resource controller:

php artisan make:controller ArticleController --resource

AJAX requests in Laravel 6

Let's add the routers to this controller. Open the routes/web.php file and add:

Route::resource('/article', 'ArticleController',['only' => ['index', 'store', 'show', 'destroy']]);

And let's add an ArticleController to the test in the index method of the controller:

public function index()

{

return "INDEX";

}

Let's go <domain>/article. In my case, it's http://lara.loc/article

AJAX requests in Laravel 7

Excellent, it works.

Conclusion of all articles.

The index method of the ArticleController controller is responsible for the output of all articles. Let's describe it:

public function index()

{

$articles = Article::all(['id','title']);

return view('index',['articles' => $articles]);

}

We get all the records from the articles table (but only get the id and title fields) and pass everything to the index.blade template.php and don't forget to add:

use App\Article;

Let's create an index.blade.php template in the resources/view directory and put the following code in it:

<!DOCTYPE html>

<html lang="en">

<head>

<metacharset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="csrf-token" content="{{ csrf_token() }}">

<title>List of Articles</title>

<!-- Bootstrap -->

<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->

<!-- WARNING: Respond.js doesn't work if you view the page via file:/// -->

<!--[if lt IE 9]>

<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>

<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

<![endif]-->

</head>

<body>

<div class="container">

<h1>List of articles</h1>

<div class='row'>

<button type="button" class="btn btn-primary btn-lg pull-right" data-toggle="modal" data-target="#addArticle">

Add article

</button>

</div>

<br />

<div class='row @if(count($articles)!= 0) show @else hidden @endif' id='articles-wrap'>

<table class="table table-striped ">

<head>

<tr>

<th>ID</th>

<th>Title</th>

<th></th>

</tr>

</thing>

<body>

@foreach($articles as $article)

<tr>

<td>{{ $article->id }}</td>

<td><a href="{{ route('article.show', ['id' => $article->id]) }}">{{ $article->title }}</a></ td>

<td><a href="" class="delete" data-href=" {{ route('article.destroy',$article->id) }} ">Delete</a></td>

</tr>

@endforeach

</tbody>

</table>

</div>

<div class="row">

<div class="alert alert-warning @if(count($articles) != 0) hidden @else show @endif" role="alert"> No entries</div>

</div>

</div>

<!-- Modal -->

<div class="modal fade" id="addArticle" tabindex="-1" role="dialog" aria-labelledby="addArticleLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

<h4 class="modal-title" id="addArticleLabel">Add Article</h4>

</div>

<div class="modal body">

<div class="form-group">

<label for="title">Title</label>

<input type="text" class="form-control" id="title">

</div>

</div>

<div class="modal body">

<div class="form-group">

<label for="text">Text</label>

<textarea class="form-control" id="text"></textarea>

</div>

</div>

<div class="modal-footer">

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

<button type="button" class="btn btn-primary">Save</button>

</div>

</div>

</div>

</div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->

<script src="{{ asset('js/bootstrap.min.js') }}"></script>

</body>

</html>  

Let's check what happened.

 

Everything works. We don't have any records in the table yet. Let's implement a method to add an article.

Adding an article using an ajax request

On the page with the list of articles, we have a button, when you click on it, a modal window appears.

 

In this window, we enter the data of the new article. And when you click the "Save" button, we transfer the data using ajax to save.

 

Let's write JavaScript, which, when clicking on "Save", will send an ajax request to the address <domain> / article (in my case, http://lara.loc/article), and pass the data by the POST method.

The first thing we will do is to add id="save" to the "Save" button. And let's write a little code in JavaScript. At the end of the index.blade file.php, after connecting the scripts, add:

<script>

$(function() {

$('#save').on('click',function(){

var title = $('#title').val();

var text = $('#text').val();

$.ajax({

url: '{{ route('article.store') }}',

type: "POST",

data: {title:title,text:text},

headers: {

'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')

},

success: function (data) {

$('#addArticle').modal('hide');

$('#articles-wrap').removeClass('hidden').addClass('show');

$('.alert').removeClass('show').addClass('hidden');

var str = '<tr><td>'+data['id']+

'</td><td><a href="/article/'+data['id']+'">'+data['title']+'</a>'+

'</td><td><a href="/article/'+data['id']+'" class="delete" data-delete="'+data['id']+'">Delete</a></td></tr>';

$('.table > tbody:last').append(str);

},

error: function (msg) {

alert('Error');

}

});

});

})

</script>

I don't think the code needs to be explained. It's just that here we pass two variables title and text to the address, which we define by the name of the thread.

Now let's describe the controller method that is called by this router (in our case, the ArticleController controller and the store method). Let's add the following code to the store method:

$res = Article::create(['title' => $request->title, 'text' => $request->text]);

$data = ['id' => $res->id, 'title' => $request->title, 'text' => $request->text];

return $data;

We can check. Let's create the first article.

 

Article added. If we open our table in the database, we will see the record.

Let's review the article.

View the article

To view the article we have the show method of the ArticleController controller, let's add the following code:

public function show($id)

{

$article = Article::find($id);

return view('show',['article' => $article]);

}

We search the database for an article by its id, and return everything to the show.blade.php template. Let's create a show.blade.php template and add the following code to it. (Let me remind you that the template, in our case, should be in resources/view)

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="csrf-token" content="{{ csrf_token() }}">

<title>{{ $article->title }}</title>

<!-- Bootstrap -->

<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->

<!-- WARNING: Respond.js doesn't work if you view the page via file:/// -->

<!--[if lt IE 9]>

<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>

<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

<![endif]-->

</head>

<body>

<div class="container">

<div class="panel panel-default">

<div class="panel-heading">

<h3 class="panel-title">{{ $article->title }}</h3>

</div>

<div class="panel-body">

{{ $article->text }}

</div>

</div>

</div>

</body>

</html>

Let's check. On the page with the list of articles click on the link with the name of the article:

AJAX requests in Laravel 7

It's cool. Our task is to implement only the deletion of the article.

Deletion of the article by ajax method.

For deleting the article, we have the destroy method of the ArticleController controller. Let's describe this method.

public function destroy ($ id)
{
Article::find ($id)->delete();
return 'ok';
}

Now in the index.blade template.php we need to implement javascript that will pass ajax data to the method to remove. However, the data is transmitted by the DELETE method.

Let's get started.

Let's add the following script to the <script section>:

$('body').on('click','.delete',function(e){

e.preventDefault();

var url = $(this).data('href');

var el = $(this).parents('tr');

$.ajax({

url: url,

type: "POST",

headers: {

'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')

},

success: function (data) {

el.detach();

},

error: function (msg) {

alert('Error');

}

});

});

Let's check what we got. Let's add a few more articles and try to delete them.

Everything works perfectly.

Conclusion.

We have put Ajax requests into practice in Laravel. Created a resource controller in which we implemented the creation of an article on ajax request, viewing the article (regular get request) and deleting the article with an ajax request.

Yes, when adding an article, we could connect WYSIWYG to the text field, as described in the article "Connecting the text (wysiwyg) editor to Laravel", we also did not do validation when adding articles. But that was not the purpose of the article and the goal we achieved: the use of AJAX requests in Laravel.