In JavaScript, navigate to a new page only after successfully transmitting data to the server

Creating a redirect page that sends data to the server before transitioning to a new page can be achieved using JavaScript as shown below.

<body>

<script type="text/javascript">

****
Discussion of cookie-related transactions
****

document.createElement("img").setAttribute("src", "server.php?param1=cookiedata");

location.href = "new_page.html";

</script>

</body>

However, there are instances where

document.createElement("img").setAttribute("src","server.php?param1=cookiedata");

is not executed before redirecting to "new_page.html". This means that the data is not sent to "server.php".

Could this issue be related to the short redirect time?

Can you suggest a solution for this problem?

Answer №1

There seems to be an issue where the request to load the source material is sometimes not sent before the redirection occurs.

To resolve this, a simple solution is to utilize the onload event to add a handler that will execute after the image has finished loading.

You can achieve this by implementing something similar to the following code snippet:

function redirectAfterTransmit() {
  window.location.href = "/new_page.html";
}

var img = document.createElement("img");
img.addEventListener("load", redirectAfterTransmit);
img.src = "server.php?param1=cookiedata";
document.appendChild(img)

Please let me know if this solution works for you!

Special thanks to Jaromanda X for their valuable input and comments.

Answer №2

Check out this link for more information: Wait for image to be loaded before going on

If you want to ensure that the "image" has been fully loaded, you may need to wait for it. This way, you can guarantee that the request has been successfully sent.

<body>

<script type="text/javascript">

****
light transaction about cookie
****

function loadSprite(src, callback) {
    var sprite = new Image();
    sprite.onload = callback;
    sprite.src = src;
}


loadSprite('server.php?param1=cookiedata', function() {
    location.href = "new_page.html";
});



</script>

</body>

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

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

Issues are arising with the .mouseover functionality within this particular code snippet

Learning Javascript has been a challenge for me so far. I tried following a tutorial, but the result I got wasn't what I expected based on the video. I'm wondering why that is and how I can fix it. I'm aiming to make a box appear suddenly w ...

What limitations prevent me from using "await .getAttribute()" in Protractor, despite the fact that it does return a promise?

I have been working on transitioning my Protractor tests from using the selenium control flow to async/await. However, I am facing an issue where it is not allowing me to use await for the .getAttribute() function. Each time I try, I receive the error mess ...

Determine whether the browser is being used on an Android or iOS device

Is there a dependable method to alter buttons and text on a mobile site based on whether the user is using an Android or iOS browser? ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

Express.js allows users to define a parent root folder domain

My Express Node.js application is structured as follows: app.get('/', page.index); //Add new, edit and delete form app.get('/approval', page.approval); //Task to approve/reject the subordinate form app.get('/task', page.task ...

Experimenting with a Jest test on an express middleware

I'm currently faced with a challenge in testing my controller (express middleware) using Jest. To better illustrate the issue, I will share the code snippet below: import request from 'utils/request'; import logger from 'config/logger& ...

Attempting to manipulate the selected tab material using a custom directive with two-way data binding

I've been struggling to change the tab using code and can't seem to figure out what's causing the error. It works fine when I use the controller to change the variable, but when trying to bind it through a directive, it breaks. var app = an ...

Using jQuery to toggle sliding the information above a div

I am facing an issue with my customized sliding menu. The menu slides over the image but not over the content-div, pushing it aside. I have tried to fix this problem but haven't found a solution yet. My goal is for the menu to slide over all divs and ...

The 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable. This is what I currently have: this.testTheRest = function() { $http.jsonp(&a ...

CAUTION: Attempted to initialize angular multiple times...all because of jQuery...such a puzzling issue, isn

I am attempting to comprehend the situation at hand. The warning is clear, and I acknowledge that in my application, with the provided code and structure, the ng-view runs twice ('test' is logged twice in the console, indicating that angular is l ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

Oops! It seems like there was a mistake. The ReferenceError is saying that Vue is

I've been working on creating a new app, but I keep running into an issue. Unidentified Reference Error: Vue is not recognized. <template> <v-app> <div id="example-1"> <v-btn v-on:click="counter += 1">Add 1</v-bt ...

The sorting function in Vue.js, _.orderBy, seems to be having trouble sorting

UPDATE This is the json data retrieved through an API using axios. bannerData= [ { "id": 118, "title": "Geruchsbel\u00e4stigung", "location": "DOR", "pressInformation": [ { ...

I am attempting to load the ajax content into separate divs simultaneously

When I attempt to load the ajax into two separate divs, I notice that despite calling for data to be placed in two different divs within the ajax code, it all ends up in one div. <script>$(document).ready(function(){ $.ajax({ url: "http: ...

Can you guide me in utilizing this API endpoint efficiently to enable search functionality using React Query?

const { isLoading, isError, data, error, refetch } = useQuery( "college", async () => { const { result } = await axios( "http://colleges.hipolabs.com/search?name=middle" ); console.log(&quo ...

Display sub navigation when clicked in WordPress

I currently have the default wordpress menu setup to display sub navigation links on hover, but I am interested in changing it so that the sub navigation only appears when the user clicks on the parent link. You can view my menu here https://jsfiddle.net/f ...

Accessing data from Execution Contexts in JavaScript

var value = 10; var outer_funct = function(){ var value = 20; var inner_funct = function(){ var value = 30; console.log(value); // displays 30 console.log(window["outer_funct"]["value"]); // I want to log the value 20 her ...

How to link an external CSS file to a Vue.js project

I created a new project using @vue/cli and now I want to add an external CSS file to my App.vue Here's what I attempted: <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | ...