0

I am trying to create a redirect page which sends data to the server before transitioning to a new page, with javascript like following code.

<body>

<script type="text/javascript">

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

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

location.href = "new_page.html";

</script>

</body>

However, before redirecting to "new_page.html", sometimes

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

is not called, and cannot send a data to "server.php".

Is it a problem that the redirect time is short?

Could you tell me how to solve?

supermonkey
  • 631
  • 11
  • 25

2 Answers2

0

The problem is that sometimes the request to load the source material for the is not sent before the redirection happens.

The solution is simple: You can use the onload event to add a handler which is called after the img has been loaded.

so something like this

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

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

Let me know if this helps!

edit: thanks Jaromanda X for comments

Community
  • 1
  • 1
jakee
  • 18,486
  • 3
  • 37
  • 42
0

have a look at this: Wait for image to be loaded before going on

you might want to wait for the "image" to be loaded. then you are sure the request has been 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>
Community
  • 1
  • 1
swisswiss
  • 335
  • 3
  • 13