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

Troubles encountered while processing STL file readers

Utilizing STLLoader.js, I am able to render components successfully, however, they all appear with one uniform color which does not resemble real-world components. The image above showcases my implementation in Three.js using STLLoader.js (Binary STL file ...

retrieving session variables from the server side in javascript

I have set a session variable in the backend (code-behind ascx.cs page) and now I need to access that same value in a checkbox checked event using JavaScript. Below is my JavaScript function code: $(document).ready(function () { $('#<%= gvPR ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...

Switching between click and mouseenter in Angular 2+ is made easy with

I am currently working on developing a component for my application's menu. One of the requirements is that the sub-menus should open on mouseenter when the menu is in compact mode, and on click when it is in wide mode (both of these are defined as cs ...

What could be the reason for the failure of the .is(":hover") method?

Here is some code I'm using to fade out certain elements on a webpage if the mouse hasn't moved for a period of time: idleTime = 0; var idleInterval = setInterval(function() { idleTime++; if (idleTime > 1) { var isHovered = $ ...

Guidance on editing list items individually using jQuery from separate input fields

Working with li presents some challenges for me. On my webpage, I have an input field that dynamically adds values to a list. However, the function to edit these values is not working properly. After editing an li element, it deletes all classes and span ...

Is it better to store CSS and JavaScript in separate files or within the main HTML document

While the best practice is to place JavaScript and CSS code in separate files (such as .js and .css), many popular websites like Amazon, Facebook, etc. often include a large portion of their JavaScript and CSS code directly within the main HTML page. Whic ...

Examining the version of a node module installed in the local environment and comparing it

One of the reasons I am asking this question is because I have encountered challenges while collaborating with other developers. At times, when other developers update node module versions, I forget to install these new modules after pulling the latest co ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

creating a project using Yeoman

I'm attempting to create a project using Yeoman from a template. I am able to successfully copy all files from the Portanova template folder, but I encounter an error when trying to copy a file from another template folder and add it to my project. Th ...

What is the best way to prevent the table from being added again once it has been displayed?

I'm faced with the task of displaying an HTML table in a popup window when a button is clicked, using Bootstrap modal functionality. This scenario is similar to a preview function where user input is displayed in a table when a preview button is click ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...

Adding a dynamic key-value pair object to an array using the JS push method

In my programming challenge, I am dealing with an array of objects that have dynamic keys and values. The structure is a bit complicated, but here's a simplified version: let products_row = [ { id: 1, category_id: 11, options: { &a ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

Adjusting the devicePixelRatio in Three.js to optimize rendering with CSS3DRenderer

I am looking to display a <div> element (specifically, one from the ECharts library) using the Three.js CSS3DRenderer and combine it with WebGL content. However, I have noticed that when the <div> has fixed width and height, the rendering qua ...

What is the best way to play a video from a certain time point in a React application?

How can I make my component automatically play from a specific time like 00:07:12,600 instead of starting from the beginning? import style from './Hero.module.css'; import Image from 'next/image'; import ReactPlayer from 'react-pla ...

Issue with displaying options in Angular2 v2.4.9 HTML select element

Ever since I made the transition from AngularJS to Angular2, I've been facing a peculiar issue. The select element's options data is fetched from a Solr query, which always returns a 200 response with the data in a timely manner. However, the pr ...

Getting Errors When Retrieving Data with Apostrophe Symbol ' in Node.js

I am currently developing a Next.js API page to extract data from a series of URLs. Interestingly, the URLs containing an apostrophe character ' fail to return any data, while those without it work perfectly fine. Surprisingly, when I execute the same ...

How to visually deactivate a flat button ( <input type="button"> ) programmatically with JavaScript

I am facing an issue with my buttons. I have one regular button and another flat button created using input elements. After every click, I want to disable the buttons for 5 seconds. The disable function is working properly for the normal button, but for th ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...