Trouble with the Ajax search feature in Laravel

No data is currently being displayed;

console:

finished loading: GET "http://todolist.local/teachers/search?text=a".

I am attempting to display results in the tbody when a user types something in the search bar.

Ajax code:

<script>
$(document).ready(function(){
        $('#searchname').on('keyup', function(){
                var text = $('#searchname').val();
                $.ajax({
                        type:"GET",
                        url: 'teachers/search',
                        data: {text: $('#searchname').val()},
                        success:function(data){
$('tbody').html(data);
}
                });
        });
});
</script>

web.php:

Route::get('/search', 'TeachersController@ajaxsearch');

Search Controller:

public function ajaxsearch(){
$searchname = Input::get ( 'searchname' );
  if($searchname != ""){
  $teacher = Teacher::where ( 'efirst', 'LIKE', '%' . $searchname . '%' )->paginate(10);
  return response()->json($teacher);
}
}

view:

<div class="input-group stylish-input-group">
                        <input type="text" id="searchname" name="searchname" class="form-control"  placeholder="Search..." >
                   <span class="input-group-addon">
                            <button type="submit" class="btn btn-primary">
                                <span class="glyphicon glyphicon-search">Search</span>
                            </button>
                        </span>
                    </div>

Answer №1

Here's the solution you've been looking for.

HTML:

  <div id="searchData"></div>

JS:

$(function(){
    $('#searchInput').on('keyup', function(){
        $.get('/results/search/'+$(this).val(), function(response){
            $('#searchData').html(response);
        });
    });
});

Controller:

public function fetchResults(string $value = null){
    return $value ? Result::whereRaw("UPPER(result_name) LIKE '%".strtoupper($value)."%'")->paginate(10) : [];
}

Route:

Route::get('/results/search/{value?}', 'ResultsController@fetchResults');

UPDATED VERSION POST DISCUSSION

HTML:

  <ul id="searchData"></ul>

JS:

$(function(){
    var $searchData=$('#searchData');
    $('#searchInput').on('keyup', function(){
        $.get('/results/search/'+$(this).val(), function(results){
            $searchData.empty();
            for (var i=0; i<results.length; i++){
                $searchData.append('<li>'+results[i].result_name+' <a href="/results/edit/'+results[i].id+'">edit</a></li>');
            }
        });
    });
});

Controller:

public function fetchResults(string $value = null){
    return $value ? Result::select('id','result_name')->whereRaw("UPPER(result_name) LIKE '".strtoupper($value)."%'")->offset(0)->limit(10)->get() : [];
}

Route:

Route::get('/results/search/{value?}', 'ResultsController@fetchResults');

Answer №2

Have you heard of the error function in jQuery Ajax?

$(document).ready(function(){
        $('#searchname').on('keyup', function(){
                var text = $('#searchname').val();
                $.ajax({
                        type:"GET",
                        url: 'teachers/search',
                        data: {text: $('#searchname').val()},
                        success:function(data){$('tbody').html(data);},
                        error:function(jqXHR){alert(jqXHR.status);} 
                });
        });
});

You should give this code snippet a try. It will display an error message if one occurs, and remember to enclose text in inverted commas as key value pairs.

Answer №3

You need to make a correction in your search controller by using the correct input name. Here is the corrected code:

public function ajaxsearch(){
$searchname = Input::get ( 'text' );
  if($searchname != ""){
  $teacher = Teacher::where ( 'efirst', 'LIKE', '%' . $searchname . '%' )->paginate(10);
  return response()->json($teacher);
}
}

Answer №4

To begin with, try visiting the URL manually and entering parameters.

If you receive a response, it indicates that your PHP is functioning correctly.

If you encounter an error, it means you are using the GET method. Be sure to pass the variable argument in the Route

Route::get('/search/{searchName}', 'TeachersController@ajaxsearch');

and make necessary corrections in your controller

public function ajaxsearch($searchname){
   if($searchname != ""){
       $teacher = Teacher::where ( 'efirst', 'LIKE', '%' . $searchname.'%' )->paginate(10);
       return response()->json($teacher);
   }
}

Next, utilize the $.get method in JQuery for AJAX requests using the GET Method

<script>
    $(document).ready(function(){
        $('#searchname').on('keyup', function(){
           var text = $('#searchname').val();
            $.get(urlHere, function(response){
                console.log(response);
            });
        });
     });
</script>

Check your console tab for the response

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

Generating JSON responses using Django REST framework to facilitate table visualizations on the front end

I am facing an issue with my django-rest-framework where I am trying to display a table using the Google Chart data drawing library. However, I keep encountering an error message saying "You called the draw() method with a String rather than a DataTable or ...

The complexity of managing multiple parameters in Laravel routing can often cause conflicts with other routes

Is there a way to set up a specific URL structure for blog posts with 2 parameters, like this: http://mydev.io:8000/@boss/blog_post_slug In Laravel, I have been using the following route definition to achieve this: Route::get('/{username}/{slug}&ap ...

Extract data from an ajax request in an AngularJS directive and send it to the controller

I am currently experimenting with integrating the jQuery fancy tree plugin with Angular. The source data for the tree is fetched through an ajax call within my controller. I am facing a challenge in passing this data to my directive in order to load the tr ...

delaying the alteration of an image attribute following an AJAX call

After clicking on a button, a function is triggered (think of it as a published/unpublished button). Immediately after the function is activated, I change the element to display a loader gif. function updateStatus(event, status, element, data, action) { ...

Ways to handle the ajax callback content

I'm dealing with an AJAX code that looks like this: var req = new XMLHttpRequest();<br> req.open('GET', 'http://www.example.org/', false); req.send(null);<br> if(req.status == 200)<br> var response = http_att ...

Retrieving the current user using Vue/Axios within the Laravel framework

Currently, I am looking for the most efficient way to load the current user into my Vue app in order to access the username and ID from any component or route. At this point, I have attempted the following approach: app.js new Vue({ el: '#app&apos ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

Unable to clear Laravel Application cache using deployment script

I'm currently working on setting up a deployment script for my Laravel 5 application to integrate with CodeShip. However, I've encountered an issue when it comes to clearing the application cache during the deployment process. Even after running ...

Can I receive a PHP echo/response in Ajax without using the post method in Ajax?

Is it feasible to use Ajax for posting a form containing text and images through an HTML form, and receiving the response back via Ajax? Steps 1.) Include the form in HTML with a submit button. 2.) Submit the form to PHP, where it will process and upload ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

Basic use of AJAX for sending the value from jQuery's datepicker

As a novice in JavaScript and AJAX, I'm hoping for your patience as I navigate my way through. In the scope of this project, I am utilizing the CodeIgniter framework. My objective is to implement a datepicker and transmit its value via AJAX. Below is ...

the modal body is taking longer than expected to load with ajax

I have a unique modal that I'm filling with dynamic data through an Ajax GET request upon modal load. Interestingly, the data is not fetched or added to the modal body unless I trigger an alert first. The structure of my modal is as follows: <div ...

Ajax response values overlap

I am developing an application that requires multiple Ajax requests, but I encountered a problem where I am receiving the same response values for both requests. Each request must include a data field called activityCode, yet I keep getting the value of Sc ...

Having trouble sending data to an API through jQuery: the function is not functioning properly

Currently, I am in the process of developing an HTML form that allows users to input values into text fields and submit them to an external API called ThingSpeak. This API then uses the received values to generate a plot displayed within an iframe. Althoug ...

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

What is the best way to assign a jQuery variable to a PHP variable?

After spending some time searching and working on it, I still can't figure out the answer to this straightforward question. Here is the code I have been struggling with. <script> function calculate() { var total = (parseInt($('#stude ...

Searching in Django utilizing jQuery keyup

When implementing a search functionality using the jQuery keyup function, I have set up my views to display the searched contacts in a template. Here is how my views are structured: def contacts_profile(request, search_id=None): contact = Invitation.o ...

Calling an ajax request to view a JSON pyramid structure

My experience with ajax is limited, so I would appreciate detailed answers. I have a Pyramid application where I need to load information via ajax instead of pre-loading it due to feasibility issues. I want to retrieve the necessary information through a ...