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

What is the best way to send data back to a separate JavaScript file in ExtJS when working with records in a

I'm currently working on implementing a pop-up editing feature on a grid in extjs4. Progress so far includes successfully transferring the grid record to a popup panel located in a separate JavaScript file using the following code: handler: function( ...

Rearrange elements within a div by clicking a button

I want to shuffle div elements with a click of a button using a dissolve animation in HTML5. An example of what I am looking for is similar to this website When you scroll on the page, there are links such as All, Intro, Solution. Clicking on any link sh ...

Using Jquery to insert content into HTML using the .html() method is not possible

I am inserting Dynamic Code into a Div via Ajax and I also need to include some Javascript, but it's not displaying in the code. Below is the code snippet: $.ajax({ url: "ajax_add_logo_parts.php", data: 'act=getPartIm ...

Tips for altering the appearance of a button:

Upon clicking the subscribe button and successfully subscribing, I want to display an unsubscribe option in my code. To achieve this, I have created two separate divs for each button, thinking that we could toggle between them. <div id ="subscribe_ever ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

What is the best way to use PHP to send an GCM downstream message via HTTP POST request?

I'm still getting the hang of PHP syntax. While I know how to handle HTTP POST and GET requests in PHP, sending a POST request without using a form is something that puzzles me. I want to figure out how to do it with just a PHP script instead of relyi ...

JQuery hover effect for dynamically added elements

Currently, I am working on a webpage that will trigger an ajax call upon loading. The response data in JSON format will be processed and the elements will then be added to the DOM as shown below: $.ajax({ type: 'POST', url: "http://mysite.de ...

Sending a concealed input according to the chosen option

I'm attempting to send some hidden values to a Servlet via a form, but my goal is to only pass them if the user chooses a specific option. <!-- FORM ABOVE --> <input type="hidden" name="foo" id="foo" value="foo"> <input type="hidden ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

What is the method for attaching multiple listeners to an element?

For example: v-on:click="count,handle" I posted this question in the Vue gitter channel, but received advice to use a single listener that triggers others. If using one listener is the recommended approach, I am curious to understand why. Is having multi ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Unable to maintain sequential IDs for textboxes using Javascript or JQuery

I am encountering a problem involving the addition and deletion of multiple text boxes using buttons. The issue lies in maintaining sequential IDs for each textbox. Below is an explanation of my code: <div class="form-group" id="intro-box"> < ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Tips for providing support to a website without an internet connection

I am in the process of creating a sales platform for a grocery store that utilizes PHP/MySQL. I have come across some websites that are able to fully reload and function even without internet access. For instance, when I initially visited abc.com, everyth ...

Encountered an issue while attempting to include multiple JavaScript sources. Please review your configuration settings for the javascripts.join

While setting up a basic app using phoenix-elixir and brunch, encountering the following error: 23 Mar 10:18:10 - warn: node_modules/phoenix/priv/static/phoenix.js compiled, but not written. Check your javascripts.joinTo config 23 Mar 10:18:10 - war ...

Tic-Tac-Toe: The square's value stays unchangeable

Currently, I am working on creating a tic-tac-toe game using pure vanilla Javascript, so I am aiming to keep it as simple as possible. I have run into an issue and need some guidance. The main requirement is that once a square has been clicked and filled ...

Troubleshooting: Issues with updating a text field in Vue test utils using Jest

Hello, I am new to Jest and unit testing. I have a question about how to set the value of a text input using Vue Test Utils. Here is the code for my custom text input component: <input v-model="local_value" @keyup.enter="submitTo ...

What is the most efficient way to send an email with all fields from a massive PHP-enabled web form containing approximately 75 fields?

In the past, I have successfully created Ajax-enabled contact forms with around 12 fields. Now, I am facing a new challenge - developing a PHP-enabled web page for job applications that includes approximately 100 fields. My previous method of sending requ ...

A blank screen of errors pops up when attempting to update through a form

Encountering a white error screen when attempting to add an item using a form in Python / Django. I'm currently debugging the issue but lacking information. Any guidance on where to look next would be greatly appreciated. Models.py from __future__ i ...