Is it possible for an ajax request to complete even if a page redirection occurs?

In my current project, I am attempting to generate a temporary URL for a local image and submit it to Google for an Image Search. I need this URL to be transient and automatically deleted after the search is complete. Here's the code snippet that I have implemented:

// Function to retrieve a dynamic URL for performing an image search using Google.
function getImageURL() {
    var xml = new XMLHttpRequest();
    xml.onreadystatechange = function () {
        if (xml.readyState == 4 && xml.status == 200) {
            deleteImageURL(); // Initiate asynchronous call to the server to delete the URL
            window.location.href = 
                "https://www.google.com/searchbyimage?site=search&sa=X&image_url=" 
                + xml.responseText; // Generated image URL
        }
    }
    xml.open("GET", "REST_ENDPOINT", true);
    xml.send();
}

The getImageURL() function contacts the server, deletes the URL upon completion, and redirects the page. The deleteImageURL() function triggers another AJAX call for URL deletion. Despite loading the Google page successfully, there may still be timing issues as the URL might not finish deleting before the redirect occurs.

My query is whether deleteImageURL() will properly delete the image URL even after the page has been redirected, or will it halt midway through the process?

UPDATE: Considering suggestions regarding potential race conditions, I revised the code as follows:

// Function to obtain a dynamic URL for conducting a Google image search.
function getImageURL() {
    var xml = new XMLHttpRequest();
    xml.onreadystatechange = function () {
        if (xml.readyState == 4 && xml.status == 200) {
            deleteImageURL(xml.responseText);
        }
    }
    xml.open("GET", "REST_ENDPOINT" + id + "/public_url", true);
    xml.send();
}

// Function to remove the image URL.
function deleteImageURL(imageURL) {
    var xml = new XMLHttpRequest();
    xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
    xml.send();
    window.location.href = 
            "https://www.google.com/searchbyimage?site=search&sa=X&image_url=" + imageURL;
}

This revised code consistently performs well in tests. While there may still be some race conditions present, the functionality appears to be working correctly thus far.

Thank you for your assistance.

Answer №1

Utilizing the "deleteImageURL()" function ensures that the image URL is successfully deleted even if the page redirects before completion. For more information, check out: Should I wait for ajax to complete to redirect a page?

Answer №2

While the server will continue to process the request triggered by deleteImageUrl, it is vital to note that if the page in the browser unloads before completion, you may not be able to handle a callback.

Answer №3

In the scenario where deleteImageURL(); includes an asynchronous call, it is essential to initiate the redirect once the call has been successfully completed. Your code should operate smoothly if the call is synchronous. Although the origin of deleteImageURL(); remains uncertain and specifics are lacking, it is advisable to follow a similar approach as with getImageURL().

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

Due to a glitch in the firebase cloud function, the payment is not going through

I have developed a react-redux application with Firestore as the database and now I want to integrate Firebase Cloud Functions to handle Stripe payments. Here is how it's set up: Below is the action method for checkout, which processes token and amo ...

Determining the size of a custom-typed array in Typescript

Can anyone explain how to find the length of a custom typed array? For example: type TMyArray = IProduct[] interface IProduct { cost: number, name: string, weight: number } So, how can we determine the length in this case: const testArr: TMyArray ...

Can you explain the contrast between EJS's render() function and renderFile() method?

const express = require('express'); const ejs = require('ejs'); const app = express(); app.engine('ejs', ejs.renderFile); app.get('/', (req, res) => { res.render('index.ejs', { ...

Is there a way to personalize the header outline of the mui-material datagrid?

Can someone help me modify the appearance of the Mui Datagrid outline to something different than its default setting? I'm having trouble uploading my code. Are there any reference materials or sample code snippets available for this modification? ...

Eliminate Redundancy with Knockout.js Copy Prevention

When I combine both ko.js files, one of them ends up being overshadowed by the other. Specifically, the second one stops working while only the first one remains functional. How can I merge these files together to ensure they work properly without any conf ...

Guide on retrieving the content type field value in Drupal and transferring it to a JavaScript file

In my custom Drupal theme, I have included a field for a SoundCloud URL with the machine name (field_soundcloud_url_). I am attempting to use a JavaScript file that will function based on the value of this variable. However, it seems to not be working as e ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

The index on ref in MongoDB does not seem to be yielding any improvements

I've encountered a performance issue with my model: const PostSchema = new mongoose.Schema( { _id: mongoose.Schema.Types.ObjectId, workSpace: { type: mongoose.Schema.Types.ObjectId, ref: 'Workspace&apos ...

Comparing AngularJS $interpolate with $filter

AngularJS offers different tools for manipulating data displayed to users. While $filter is commonly used for formatting data, $interpolate enables real-time updates within a text string. Do $interpolate and $filter have any connection? How do they differ ...

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

Creating a Vue single-page application (SPA) and concealing the .vue files upon rendering in the

I have a Single Page App built using Vue.js and hosted on a node.js server. While the app is still in development, it will eventually be accessed by external customers. Due to the sensitive data involved, we want to prevent users from seeing the .vue files ...

PHP not receiving data from jQuery Ajax (POST) request

Below is an Ajax function that sends data from a page to the same page for interpretation by PHP. When using Firebug, it is observed that the data is being sent, but not received by the PHP page. However, if we switch to a $.get function and retrieve the ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

Combining ajax and jsp to fetch data for a servlet

In my JSP file, I have two text fields - signUp and post. I want the post text to be sent to a servlet using AJAX function while the signUp text should be sent in the usual way through request.getParameter(). Can these two functionalities be combined with ...