When making an Ajax post request, the loading indicator may not appear

I've implemented the jQuery code below for an autocomplete input field, but I'd like to have a spinner display while waiting for the response from the server.

In my code, I'm using search: to show the loading div and open: to hide it. The success function is then used to display the result.

 $(document).ready(function(){  
      $('#search_field').keyup(function(){  
           var search = $(this).val();  
           if(search != '')  
           {  
                $.ajax({

                     url: 'search.php',  
                     method: 'POST',  
                     data: {search:search},  

                     search: function()
                     {
                         $('#search_loader').fadeIn('fast', 'swing');
                     },

                     open: function()
                     {
                         $('#search_loader').fadeOut('fast', 'swing');
                     },

                     success: function(data)  
                     {     
                         if(data == '') {
                             $('#autocomplete_result').fadeOut('fast', 'swing');
                         } else {
                             $('#autocomplete_result').fadeIn('fast', 'swing'); 
                             $('#autocomplete_result').html(data); 
                         }
                     }


                });  
           }  
      });  


 }); 

Unfortunately, neither search: nor open: seem to be working as expected. As someone new to JS, can anyone provide some guidance on what might be incorrect in my implementation?

Answer №1

Take a look at http://api.jquery.com/jquery.ajax/. There are no open and search options available. Consider using beforeSend and complete functions, and set the fadeIn fadeOut effect to "slow".

$(document).ready(function(){  
      $('#search_field').keyup(function(){  
           var search = $(this).val();  
           if(search != '')  
           {  
                $.ajax({    
                     url: 'search.php',  
                     method: 'POST',  
                     data: {search:search},    
                     beforeSend : function()
                     {
                         $('#search_loader').fadeIn('slow', 'swing');
                     },   
                     complete : function()
                     {
                         $('#search_loader').fadeOut('slow', 'swing');
                     },

                     success: function(data)  
                     {     
                         if(data == '') {
                             $('#autocomplete_result').fadeOut('fast', 'swing');
                         } else {
                             $('#autocomplete_result').fadeIn('fast', 'swing'); 
                             $('#autocomplete_result').html(data); 
                         }
                     }
                });  
           }  
      });  
 }); 

Answer №2

To use Ajax, you can follow this syntax:

$.ajax({
    url: 'your_url',
    method: 'get', // or post
    data: {
      var1 : val1,
      var2 : val2
    },
    before:  function(){

    },
    onComplete: function(){

    },
    success : function(response){

   }
});

There is no specific `search` function defined for Ajax. If needed, you can also invoke them within before() or onComplete()

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

Tips for showcasing the contents of a file on a website

Greetings! I am a newcomer to the world of web development and I am seeking a method to showcase file content on a webpage. Presently, I have succeeded in loading text file content and displaying it in a large text box. However, I am now interested in di ...

Combining JSON objects to form a new object within a JSON object using JavaScript

Here is the JSON data that I have: {"rows":[ {"shiftId":1,"shift":"Morning","item":"Tea","value":20}, {"shiftId":1,"shift":"Morning","item":"Coffee","value":30}, {"shiftId":2,"shift":"Evening","item":"Tea","value":40}, {"shiftId":2,"shift" ...

Error: 'require' function is not recognized in the latest JavaScript file

I am interested in using anime.js. To install this library, I need to follow these steps: $ npm install animejs --save const anime = require('animejs'); The code should be written in a js file named "anime.js" Here is the code for "anime.js": ...

Failing to retrieve data from Ajax response

When handling requests in a servlet, the following code snippet processes the request received: Gson gson = new Gson(); JsonObject myObj = new JsonObject(); LoginBean loginInfo = getInfo(userId,userPwd); JsonElement loginObj = gson.toJsonTree(loginInfo) ...

Here's a unique rewrite: "Learn how to manipulate the CSS class of a textarea element (specifically in NicEdit) by utilizing the addClass

I am currently validating a textarea using the NicEdit plugin. var getContent = nicEditors.findEditor("SubSliderDescription").getContent(); bValid = bValid && checkBlankTextArea(getContent, "SubSliderDescription") function checkBlankTextArea(o, ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

Is it possible to continuously generate webpages using AJAX?

Is there a way to achieve an infinite scrolling effect in all directions using ajax requests without the need for flash or silverlight? If anyone has an example of this, I would love to see it! Thank you for your time. ...

What is the mechanism by which sending data directly to the response object displays content to the user?

What exactly does the .pipe(res) segment of the code snippet from that article do at the end of the stream? fs.createReadStream(filePath).pipe(brotli()).pipe(res) I have a basic understanding that the first part reads the file and the second compresses i ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

Utilizing Firebase 9.0.1 Functions in Vue.js 3

As a newcomer to Vue, I decided to tackle my second tutorial which involved integrating Firebase backend with Vue. However, the tutorial was based on Vue 2 and an older version of Firebase. Determined to stay current, I set out to replicate the project usi ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...

I am currently experiencing difficulties with loading files in Magento even though they are present on the server

I am experiencing difficulties with a Magento 1.5.1 installation that was not a fresh setup, but rather one that was transferred to another server (files and database copied over). The issue I am facing is related to the failure of my Javascript files to ...

Instructions for overlaying a text onto the select input field in DataTables

I am currently utilizing the DataTables select input feature to capture only the first three columns of data. However, I would like to enhance this by adding a text element above the select inputs within the DataTables interface. Is there a way to achieve ...

The functionality of the Facebook app will be compromised if the website is not specified

I've recently integrated the Like 2 Unlock for jQuery plugin into my WordPress plugin. By using this plugin, I am able to lock certain settings content that can only be accessed once a user has "liked" it. This allows people to manage their settings ...

The scrolling event on the div is not triggering

I'm struggling with this piece of code: const listElm = document.querySelector('#infinite-list'); listElm.addEventListener('scroll', e => { if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) { th ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...