Broaden the reach of the ajax .done function to encompass the surrounding function

It seems like my previous attempts to find a solution for the function below were unsuccessful:

    function countNoFilters(keyword){

    keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val();

    var getResults = $.ajax({
        type:"GET",
        url:"",
        data:keyword

    });

    getResults.done(function(data){
        var results = $(data).find(".class").length;
        return results;
    });
} 

How do I make the function 'countNoFilters("keyword")' return the value from the .done function within it? It would be greatly appreciated if someone could provide a functional example tailored to this specific function.

Answer №1

One approach you could take is by utilizing a function variable wherein the `gresult` variable gets assigned within the done function and then returned at the end of the `countNoFilters` function like so:

function countNoFilters(keyword){

    var gresult;

    keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val();

    var getResults = $.ajax({
        type:"GET",
            url:"",
            data:keyword

    });

    getResults.done(function(data){
        var results = $(data).find(".class").length;
        gresult = results;
    });

    return gresult;
} 

Answer №2

To ensure synchronous execution, remember to include async:false. Execute the code snippet provided below:

function findNoFilters(keyword){

    var searchResult;

    keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#hidden-keyword").val();

    var fetchResults = $.ajax({
        type:"GET",
            url:"",
            data:keyword,
            async:false
        });

    fetchResults.done(function(data){
            var resultsCount = $(data).find(".class").length;
            searchResult = resultsCount;
        });

    return searchResult;
} 

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

Reactjs slider causes unexpected useState behavior

I created an autoplay Slider with three cards using the useEffect hook. However, the manual "previous" and "forward" buttons are not functioning correctly. The useState function is not updating values as expected, leading to unexpected changes in state. ...

Tips for navigating to an external website through GraphQL

I am currently utilizing Node.js and Front-end on Next.js. I have a GraphQL server with a GetUrl method that returns a link (for example: ""). My goal is to redirect a client who made a request to that page with a Basic Auth Header. From what I understan ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

I require fixed headers that no longer stick once reaching a specific point

I have a setup where the names and occupations of participants are displayed next to their artworks, and I've made it sticky so that as we scroll through the images, the names stay on the left. Now, I want the names to scroll out once the images for e ...

The barcode is not displaying when using javascript:window.print() to print

I am currently developing a Mean Stack App where I have a requirement to display a barcode. To achieve this, I am utilizing an AngularJS directive for generating a 128 barcode, and it is being generated successfully. However, when I attempt to print by cli ...

Why won't my setTimeout function work?

I'm having trouble working with the setTimeout function, as it doesn't seem to be functioning properly. First and foremost, Player.prototype.playByUrl = function (url) { this.object.data = url; return this.play(); } The co ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon c ...

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

Unable to adjust the height of an MP4 video to properly display within a Material Box in both landscape and portrait orientations

While I have been learning JavaScript React, I encountered an issue with positioning an MP4 movie. You can view the code in this Codesandbox If you check out the FileContentRenderer.jsx file, you will see that the html5-video is used for the MP4. The g ...

What is the process for requiring web workers in npm using require()?

I have a setup using npm and webpack, and a part of my application requires Web Workers. The traditional way to create web workers is by using the syntax: var worker = new Worker('path/to/external/js/file.js'); In my npm environment, this metho ...

Using the power of ReactJS, efficiently make an axios request in the

After familiarizing myself with Reactjs, I came across an interesting concept called componentDidUpdate(). This method is invoked immediately after updating occurs, but it is not called for the initial render. In one of my components, there's a metho ...

Building a High-Performance Angular 2 Application: A Comprehensive Guide from Development to

Recently, I began developing an Angular2 project using the quickstart template. My main concern now is determining which files are essential for deployment on my live server. I am unsure about the specific requirements and unnecessary files within the qu ...

Leverage the Google Drive API for the storage of app-specific data

I'm currently developing a JavaScript application that runs on the client side and need to store a JSON object containing configuration details in a Google Drive Appdata file. Through the Google Drive API, I can successfully check for the file within ...

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

Utilizing imported components to set state in React

In my project, I created a functional component named Age and imported it into another functional component called Signup. This was done in order to dynamically display different divs on a single page based on the authentication status of the user. By sett ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Internet Explorer versions 9 and 10 do not support the CSS property "pointer-events: none"

In Firefox, the CSS property pointer-events: none; functions properly. However, it does not work in Internet Explorer 9-10. Are there any alternative approaches to replicate the functionality of this property in IE? Any suggestions? ...

Utilizing Node.js with Graphics Magick to generate high-quality cropped thumbnails without sacrificing image resolution

Is there a solution to maintain image quality when cropping and centering an image using Graphics Magick? The code I currently have reduces the fidelity of the resulting image. gm(imagePath) .thumbnail(25, 25 + '^') .gravity('Cent ...