Laravel

【Laravel】How to Search and Display Table Data Using Asynchronous Communication 【ajax, response()->json】

Introducing how to use Laravel and asynchronous communication (ajax) to search a table by an entered ID and display the retrieved data. (Laravel version 6.x)

Table Structure for Searching by ID with Asynchronous Communication

Prepare the following users table.

users Table

Name Description
id Primary key
user_name Name

Model Definition for users Table Data

* Prepare a User.php file.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

}
?>

View Definition for the ID Search Page That Searches and Displays Table Data Asynchronously

* Prepare a users.blade.php file. This page searches by ID and displays the name as the search result.

Input Form Section

* Prepare an ID search text box (user_id) and a result display text box (user_name).

<div>
	<label for="user_id">ID Search</label>
	<input type="text" id="user_id" name="user_id" value="">

	<label for="user_name">Name</label>
	<input type="text" id="user_name" name="user_name" value="">
</div>

ajax (Asynchronous Communication) Section

* Load the “jquery-3.6.1.min.js” file.
When the ID search text box (user_id) is entered, get its value and send it as a search parameter (id) using ajax.
If ajax successfully retrieves the json data, output the corresponding name to the result text box (user_name).

<script src="jquery-3.6.1.min.js" defer></script>
<script type="text/javascript">
$(function () {
var userid = "";
// Save the current this of ID search textbox for later use in the done process
function fncasyncid(event) {
  userid = event;
}

$('#user_id').on('change',function(){

    var id = $(this).val();

    fncasyncid(this);

    $.ajax({
      url: './users?id='+id,
      type: 'GET',
      dataType: "json",
    }).done(function (data) {
      // Successfully retrieved
      // Retrieved json data
      var data_stringify = JSON.stringify(data);
      var data_json = JSON.parse(data_stringify);

      // Extract each data from json
      var id = "";
      var user_name = "";

      if (data_json[0] != null){
        id = data_json[0]["id"];
        user_name = data_json[0]["user_name"];
      }

      $(userid).next('input').val(user_name);

    }).fail(function (data) {
      // Failed to retrieve
      alert('Failed to retrieve data.');
    });
});

});
</script>

Route Definition

* This is the URL for GET requests from ajax. Change as needed.

// Asynchronous ID Search
Route::get('/users', 'UsersController@index');

Controller Definition for Searching and Displaying Table Data Asynchronously

* Prepare UsersController.php, which uses the id passed as a parameter via ajax to search the users table and return user_name in json format.

Importing the User Model

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\User;   // Use User model
use DB;

class UsersController extends Controller
{

    // Output search results by ID
    public function index(Request $request)
    {
        $users = "";
	// Get id and user_name from users table where id matches
        $users = DB::select("SELECT users.id, users.user_name FROM users WHERE users.id = ".$request->id);

	// Return json format including HTTP header (application/json)
        return response()->json($users);
    }

}

 
 
* Please use at your own risk if you reuse this code.