Question

I am trying to execute a js action that automatically sends informations to the URL for future use with php. To do so, I added a "onload" event on the window object and modified the URL in the listener. This is what it looks like so far:

window.addEventListener("load", function() {
    window.location = "?test=test";
}, false);

When I load the page, the URL changes, but this is repeated over and over until the browser crashes. I was just wondering if there was a way to only execute it once.

Was it helpful?

Solution

If you don't want to use AJAX, and don't want to write JS functions to parse query strings, why not a simple:

<?php if(!isset($_GET['test'])): ?>
<script>
   window.addEventListener("load", function() {
       window.location = "?test=test";
   }, false);
</script>
<?php else: ?>

 <!--No JS written on the page, so no redirect -->

<?php endif;?>

But you really should look into AJAX, try using some JS framework like jQuery to help you in the process: http://api.jquery.com/jquery.ajax/

OTHER TIPS

Check to see if you're already ON that page, before redirecting.

Add a simple flag on the URL like so: window.location = "?test=test&second=true";

As suggested in How can I get query string values in JavaScript?

Write a function to check get the URL params in JS GetQueryStringParams()

Then as suggested by others pass a send param in while reload

window.location = "?test=test&second=true";

Use the function in JS to check if you have a URL query string second and if its not there then reload the page

if you want to pass variables do this:

<?php
    if(!isset($_GET['page'])){ //this line check if the variable field is available 
    $a = "Blank";
    }else{
    $a = $_GET['page'];
    }
?>

that is it.

You could just erase the onLoad method once it's run, like so:

<script>
function doLoadStuff()
{
    doSomeStuff();

    //Clear onLoad contents
    body.onLoad = function() {};
}
</script>
<body onLoad="doLoadStuff();">MyContent</body>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top