Add the item to a fresh array using the Ajax function

Here is an array that I have:

var arrayOfResults = []; // Results after like statement      

After making a database call, I receive a JSON result like this:

[{
            "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}",
            "pid": "{34214CCB-90C3-4D75-958B-5A1D0FBDD971}",
            "ttl": "Easter Bunny",
            "img": "/~/media/Images/Recipes/Easter/Filled Pasta/LF_Baked-Spring-Vegetables-Ravioli_920.ashx?h=910\u0026w=910",
            "url": "Some url",
            "taggedwith": ["{3A54907D-4171-4F4E-8FE8-3A38DA1E874F}", "{6CD78C6B-F435-45EC-BE16-810E80311C23}", "{74528A6F-C40B-4030-A278-A4C9A2F46A47}", "{6DC82B78-61F6-45A0-A63C-EA590BB1057E}", "{E9EF1A41-51D0-403D-9373-37B7A880B251}"],
            "articleddate": "2015-05-02",
            "tname": "Recipe",
            "rbrand": ["{1F6EDA5D-4681-40F0-B455-7C343AC25B72}"]
}, {
            "id": "{2e4b04b6-334f-42e9-afd7-ddc4e08417ad}",
            "pid": "{C611BAC8-E8E0-4693-920B-93BD5EE2386B}",
            "ttl": "Latina Fettuccini \u0026 Summer Sauce with Prawns Recipe",
            "img": "/~/media/Images/Recipes/Latina Fresh/Plain Pasta/LF_Fettuccini-Summer-Sauce-Prawns_920.ashx?h=910\u0026w=910",
            "url": "Some url",
            "taggedwith": ["{3A54907D-4171-4F4E-8FE8-3A38DA1E874F}", "{6CD78C6B-F435-45EC-BE16-810E80311C23}", "{74528A6F-C40B-4030-A278-A4C9A2F46A47}", "{6DC82B78-61F6-45A0-A63C-EA590BB1057E}", "{E9EF1A41-51D0-403D-9373-37B7A880B251}"],
            "articleddate": "2015-05-02",
            "tname": "Recipe",
            "rbrand": ["{1F6EDA5D-4681-40F0-B455-7C343AC25B72}"]
}] 

The UI contains a text field where users can enter free text.

An ajax method is called when the user types roughly 5 characters. The goal is to search for matches in the 'ttl' field of the above array based on the user input. If a match is found, the item should be added to the 'arrayOfResults'. However, despite seeing the alert message indicating a match, the item is not pushed into the new array. This is evident because the length of the array remains 0 when alerted at the end of the ajax call.

var addItem = false;

var freeText = $('#searchKeywords').val();

$.ajax({
    url: 'search?t=&s=DateDesc&type=globalsearch&q=',
    type: 'GET',
    dataType: 'json',

    success: function (searchDataList) {

        console.log(searchDataList)


        for (var i = 0; i < searchDataList.length; i++) {
            addItem = false;

            if (freeText.length > 0) { // Filter on free text

                if (searchDataList[i].ttl.indexOf(freeText) > -1) { // if title contains free text then we need to add it to the arrayOfResults[].

                    alert('found');

                    arrayOfResults.push(searchDataList[i]) // This doesn't seem to work.

                    addItem = true;

                }
            }
        } // End of for loop
    },

    error: function (request, error) {
    }
});


alert(arrayOfResults.length);

I'm unsure what's causing the issue, so any assistance would be greatly appreciated.

Answer №1

Your alert is triggering before your AJAX call finishes processing.

Because the AJAX request operates asynchronously, the console.log() statement executes before the success function is invoked, resulting in the incorrect output being displayed.

To properly display the results, ensure that you print within the success and error handlers of the AJAX request. Printing within the complete handler will not solve the issue as it runs separately from the rest of the functions due to its asynchronous nature.

Answer №2

It has been pointed out in previous responses that you should handle the data within the success block. You can achieve this directly as shown below, or for more intricate scenarios, call a separate function to manage the data at the conclusion of the success statement.

Revised code:

var userInput = $('#searchKeywords').val();

$.ajax({
    url: 'search?t=&s=DateDesc&type=globalsearch&q=',
    type: 'GET',
    dataType: 'json',

    success: function (searchDataList) {
        console.log(searchDataList);
        for (var i = 0; i < searchDataList.length; i++) {
            addItem = false;

            if (userInput.length > 0) {     
                if (searchDataList[i].ttl.indexOf(userInput) > -1) {
                    alert('found');
                    arrayOfResults.push(searchDataList[i]);
                    addItem = true; 
                }
            }
        } // End of for loop
        if (arrayOfResults.length > 1) {
           alert(arrayOfResults.length);
           console.log(arrayOfResults);
         }
    },

    error: function (request, error) {
    }
});

Answer №3

Your alert will always return 0 because AJAX operates asynchronously (the A in AJAX represents this) while you are calling your alert synchronously.

What is happening is that the AJAX request is fetching the data simultaneously as the synchronous code continues to execute. Since the AJAX request finishes after you trigger your alert, it cannot output any meaningful information.

If you wish for a function to be executed once the asynchronous request completes, regardless of its success or failure, utilize the done method in addition to success: and error:. This code block will execute when the request is finished, providing you with the accurate length.

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

Optimal methods for handling Ajax requests in the present day

Recently, I revisited some websites I co-built with a friend and was working on getting them functional again. It's been a while since I've done any AJAX work, and I'm realizing that there aren't many resources available to help trouble ...

Removing an event from Fullcalendar

With the help of a post on StackOverflow, I managed to modify my select: method to prevent users from adding an event on a date before NOW. However, there is a drawback. When a user clicks on an empty time slot and the system displays an alert message, th ...

Converting a json array into a map with the help of Underscore.js

My challenge involves parsing a JSON array into a map object, with the key being the state and the value being an array of objects that share the same state. An example JSON data set is provided below: { "totalRec": 10, "content": [ { "name" ...

The dictionary's get method is failing to properly retrieve the requested data

My goal is to send a value from a textbox to the server, search for this value in a dictionary, and display the result in a div. For instance, if my dictionary is d = {'a': "1", 'b': "2", 'c': "3"}, and I enter "a" in the text ...

The PUT rest service does not function in AngularJS version 1.0.8

I am facing an issue with my AngularJS application that has a CRUD Rest service. While the Create, Read, and Delete methods are functioning properly, the PUT method is not working. I have searched on Stackoverflow and found similar problems with accepted s ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Layout display issue post redirection in React

I am facing an issue with my app that utilizes styled-components and material-ui. I have set up private routes based on user roles, and when a non-authenticated user is redirected to the login page, the layout fails to load properly. App.tsx import React ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Retrieve content from JSON post data

I have been facing an issue where I am trying to send a JSON file from a web page to a nodeJS server. My goal is to assign the JSON file to an object on the server side and print it out in the console. Despite researching extensively online and attempting ...

How can you efficiently send JSON data from Ajax to a Servlet in a Java environment?

I am encountering a perplexing issue with sending data from my jQuery script to a servlet using AJAX. The strange part is that when I set the contentType to application/json, all values on the server side turn out to be null. However, if I remove it, the s ...

VueJS - When using common functions, the reference to "this" may be undefined

I'm struggling to extract a function that can be used across various components. The issue is that when I try to use "this", it is coming up as undefined. I'm not sure of the best practice for handling this situation and how to properly assign th ...

Does the CSV stream parser (PapaParse) cause rendering delays?

Currently, I am utilizing papa parse to fetch csv streams from my backend in order to visualize data. However, I have observed that while it is successfully invoking the callback for the data chunks, it is also causing rendering issues. I am attempting to ...

If an Angular reactive form component has a particular value

I am working with a group of radio buttons. When a user chooses the option "yes," I would like to display an additional input box on the form. Link to Code Example HTML.component <div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt- ...

Tips for choosing specific characters from a string using JavaScript

When dealing with URL strings like "example.com/Apps/Visitor/visitscanner" , "example.com/Apps/Seatings/visitscanner I am interested in extracting the directory name following the "http://example.com/Apps/" For the above examples, if the URL string is " ...

Troubleshooting Forms Authentication problem in ASP.NET ASHX 302 error situation

I've been working on an ASP.NET application using .NET Framework 4.7.2. In this app, there is a modal pop-up that allows users to enter notes and save them. However, sometimes users encounter issues when their authentication expires during the postbac ...

Enable JavaScript in Webdriver Selenium to enhance the functionality of your web

I am facing an issue with my Java program and Selenium WebDriver. The script I have does not detect the button "Open device access" because its style is set to "display: none". Usually, clicking on "Device Access" triggers JavaScript to display the "Open ...

I encountered an issue with Expo commands where it was throwing an error: "Module not found: 'minizlib'"

Every time I attempt to execute commands like expo init, expo start, or simply expo, it returns the following error message: Error: Cannot find module 'minizlib' Require stack: - /usr/local/lib/node_modules/expo-cli/node_modules/tar/lib/pack.js ...

utilizing jQuery's each method to extract data from a form and then proceeding to transmit it as an asynchronous ajax

As a developer, my goal is to write code that is concise yet meaningful. Currently, I am working on an edit profile form with around 10 text boxes and 2 radio buttons. While it's easy to retrieve values from a simple login form using jQuery like thi ...

Flashing text compatibility across all browsers

I'm looking for a way to create text that blinks on all major web browsers. Initially, I attempted using the <blink> HTML tag, but unfortunately, it only works in Mozilla Firefox. Next, I experimented with CSS: <style> .blink {text-deco ...

Ways to implement collapsible functionality into table rows

I have a table on my website and I want to initially display only 3 rows. When the user clicks on the 'more' button, I want the rest of the rows to be displayed. However, when I tried implementing this with code, I encountered rendering issues. I ...