Performing a live search using Laravel and Ajax within a Bootstrap modal frame

Looking to incorporate a search bar into the bootstrap 4 modal header and utilize ajax GET request to retrieve and display search results in the modal body.

Although the request is successful, I'm having difficulty displaying the results in the modal.

https://i.sstatic.net/T4wHF.png

Seeking guidance on how to showcase the previewed results from the request in a modal.

Controller:

public function index()
{
    ....

    //MODAL IS A PARTIAL ON THE INDEX PAGE

    return view('friends.index',compact('friends','friendRequests'));
}

public function search(Request $request)
{
    if ($request->has('name')) {
        $name = $request->query('name');
        $results = User::where('name','like','%'.$name.'%')->get();
    } else {
        $results = User::all();
    }

    //RETURNING THE MODEL PARTIAL,BUT WITH RESULTS
    return view('layouts.partials.friends.modal',compact('results'));
}

Relevant routes:

Route::get('/friends','FriendsController@index')->name('friends');
Route::get('/friends/search','FriendsController@search')
->name('searchFriend');

Index view:

<div class="container my-5">
<div class="row">
    <h4><i class="fas fa-user-friends"> Friends:</i></h4>
</div>

<div class="row">
    <button type="button" class="btn btn-outline-success mx-auto btn-lg" 
data-toggle="modal" data-target=".add-friends-modal">
        Add new <i class="fas fa-user-plus"></i>
    </button>
</div>

//MODAL PARTIAL IS INCLUDED HERE
@include('layouts.partials.friends.modal')

<hr>

@include('layouts.partials.friends.friends-list')

Modal partial:

<div class="modal fade add-friends-modal" tabindex="-1" role="dialog" 
aria-labelledby="friends-modal" aria-hidden="true">
<div class="modal-dialog modal-lg">

<div class="modal-content">

    <div class="modal-header ">
        <div class="container">
            <div class="row">
                <div class="col-6 offset-3">
                    <h5 class="modal-title text-center">Add new friend:</h5>
                </div>
                <div class="row mx-auto">
                    <form class="form-inline mt-4 mb-4" action="javascript:search();">
                        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" 
              id="search-input">
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>

            </div>
        </div>

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

    <div class="modal-body">

      //RESULTS SHOULD BE DISPLAYED HERE

      @if(isset($results) && count($results)>0)
              <ul>
              @foreach($results as $result)
                <li>{{ $result->name }}</li>
                  @endforeach
              </ul>
      @endif
  </div>

</div>

searchAJAX.js

function search() {

var userInput = document.getElementById("search-input").value;

var xhttp = new XMLHttpRequest();

xhttp.open('GET','/friends/search?name='+userInput,true);

xhttp.send();
}

Answer №1

In my recommendation, it would be better to return only data instead of a complete view. You can achieve this by implementing the following approach.

public function index()
{
    ....

    //THE MODAL IS A PARTIAL USED ON THE INDEX PAGE

    return view('friends.index',compact('friends','friendRequests'));
}

public function search(Request $request)
{
    if ($request->has('name')) {
       return User::where('name','like','%'.$name.'%')->get();
    }

    return response([]);
}

Modal Partial

<div class="modal fade add-friends-modal" tabindex="-1" role="dialog" 
aria-labelledby="friends-modal" aria-hidden="true">
<div class="modal-dialog modal-lg">

<div class="modal-content">

    <div class="modal-header ">
        <div class="container">
            <div class="row">
                <div class="col-6 offset-3">
                    <h5 class="modal-title text-center">Add new friend:</h5>
                </div>
                <div class="row mx-auto">
                    <form class="form-inline mt-4 mb-4" action="javascript:search();">
                        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" 
              id="search-input">
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>

            </div>
        </div>

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

    <div class="modal-body">
      <div id="results"></div>
  </div>

</div>

And JS File

function search() {
  var resultsDiv = document.getElementById("results");
  var req = new XMLHttpRequest();
  req.responseType = "json";
  req.open("GET", url, true);
  req.onload = function() {
    var users = req.response;
    var content = "<ul>";
    for (var user in users) {
      content += "<li>" + user.name + "</li>";
    }
    content += "</ul>";
    resultsDiv.innerHTML = content;
  };
  req.send(null);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having trouble with Fullcalendar not loading my JSON data to display events

I've been experimenting with the fullcalendar JavaScript library, but I'm struggling to load data from my MySQL database onto the calendar. When I test my db-connect.php file, it does return the first entry in the table, yet the calendar remains ...

Hidden content from Vue router view

My goal is to have the navigation pane overlaying the content of the page, but instead, it is being appended to the bottom where the end of the navigation drawer would be. I've experimented with different variations to display data using navigation dr ...

"How can I make a dropdown open and close when a button is clicked, but also close when clicking outside of it at the same

One button click opens a dropdown, and it also closes when clicked outside. toggleAllCategories() { this.setState({ isOpenAllCategories: !this.state.isOpenAllCategories }); } The issue arises when attempting to open and close the dropdown by clic ...

Every time I attempt to log in, the code keeps generating an error message net::ERR_EMPTY_RESPONSE. If successful, it should redirect to the

The code is producing a net::ERR_EMPTY_RESPONSE error when attempting to log in. The username and password are hardcoded. I simply want the admin to input their credentials on the Employee.html page, and if they match the ones in the main.js file, redirec ...

retrieve results upon expiry of time limit

What is the best way to retrieve a value after a timeout in the following function? $fetch: function($timeout) { var breadCrumbs; info = []; $timeout(function() { info = getCrumbs(); console.log(info); ...

Transferring Data between Rails and Angularjs using JSON

Utilizing Angularjs to fetch JSON data from a Rails test app deployed on Heroku is proving to be a bit challenging. Below you can find the snippets of my Angular and Rails code. An error message displayed in my Firebug console reads: "NetworkError: 404 N ...

The Power of ReactJS Spread Syntax

Currently working with React. In the state, I have an array of objects. this.state = { team: [{ name:'Bob', number:23 }, { name:'Jim', number:43 }] } My issue arises when attempting to create a copy of the arr ...

Tips for resolving the trigger problem with onChange in the PinInput Component of chakra-ui

The PinInput Component's onChange event is not functioning properly with the value in Chakra-UI. This issue causes the focus to automatically shift to the next input even when the value hasn't changed. For instance, when attempting to set the st ...

How do you effectively select tabs that are enabled using jQuery UI?

Is there a way to retrieve all the tabs that are currently enabled while multiple tabs exist and some are disabled within a jquery ui tab interface? ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...

Looking for assistance with implementing autofill functionality in CodeIgniter

Seeking assistance on creating an autofill form field in CodeIgniter 3 with AJAX. Despite my extensive search, I have not been able to make any progress. Controller: function autofill(){ $id_pemesan = $this->input->post('id_pemesan&apo ...

Unexpected box-shadow issue with Material UI's Box component

During the development of my application, I encountered an issue with rendering a list of items. The state consists of a simple array containing elements with a name, an identifier, and a selected key that determines whether special styles should be applie ...

Issue with Firefox: Click event not fired when resize:vertical is set while focusing

Issue: Firefox is not registering the first click event when a textarea has the following CSS: textarea:focus { resize: vertical; } Check out the demo: http://jsbin.com/wuxomaneba/edit?html,css,output The fix for this problem is straightforward - ju ...

Is there a way to disregard the data returned from previous AJAX calls?

I've been wondering about a strategy for managing delayed AJAX data returns in a scenario where newer calls should take precedence over earlier ones. For instance, if a first data fetch initiated at 12:01:33 is delayed and comes back at 12:01;39, whil ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

What is the best way to create a screen capture of a webpage using a URL?

Currently working on a Spring MVC website project, I have implemented a form requesting the user's website URL. Once entered, I aim to display a screenshot of the specified website for the user to view. Contemplating whether to generate the image on ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

The HTML table is not fully filled with data from the XML file

Trying to populate an HTML table using XML data retrieved from an AJAX call is proving to be a challenge for me. The main issue I am facing is the inability to fully populate the HTML table. Being new to AJAX, understanding how XML interpretation works an ...

Tips for adjusting the material ui Popper width to fit the container without disabling the portal

Currently utilizing the material-ui popper library. I am trying to allow the popper to extend outside of its container in the vertical direction. To achieve this, I have set disableportal={false}. However, upon setting disableportal to false, when assign ...