Corbin Spicer
Corbin Spicer

Reputation: 285

Javascript Refresh with only one query string

I have a page which auto refreshes using javascript and it refreshes with all the parameters in the URL, eg. server/ViewRoom.aspx?RoomID=5&ConfirmID=4834 I would only want to keep the RoomID parameter.

My code at the moment:

   <script type="text/javascript">
     var timeout = setTimeout("location.reload(true);", 50000); // How often do you want the initial page to refresh?
     function resetTimeout() {
         clearTimeout(timeout);
         timeout = setTimeout("location.reload(true);", 50000); // How often do you want the page to refresh?
     }
   </script>

How do I go about only selecting the RoomID query string for reload

Upvotes: 0

Views: 444

Answers (2)

milieu
milieu

Reputation: 36

As Edmund24 mentioned, you shouldn't need to clear the timeout since you're reloading the page, so then our code looks like:

<script type="text/javascript">
  var timeout = setTimeout("location.reload(true);", 50000);
</script>

Similarly, we don't need to keep track of the handler id, so we can disregard storing that:

<script type="text/javascript">
  setTimeout("location.reload(true);", 50000);
</script>

The major issue with Edmund's code is that, in the case that the RoomID query string is not the first query string in the URL, this will not behave as you expected. So instead, we need to go explicitly search for and grab the query string that contains 'RoomID':

<script type="text/javascript">
  setTimeout(function () {
    var domain = location.href.split('?')[0],
        queryStrings = location.href.split('?')[1].split('&'),
        roomIDqs;

    queryStrings.forEach(function (e, i, a) {
      if(~e.indexOf('RoomID')) roomIDqs = e;
    });

    location.href = domain + roomIDqs;

  }, 50000);
</script>

I haven't tested this code, but this should be the idea.

Notes:

  • ~.indexOf('other string') is a shortcut for contains(), since javascript doesn't have a built-in contains() method.
  • Array.foreach(function (e, i, a){}) -- the callback function is automatically passed the current element (e), the current index (i), and the complete array (a). We use e here to talk about the current query string.

Upvotes: 2

Edmund24
Edmund24

Reputation: 26

I don't think you need clear timeout since reload occurs.

<script type="text/javascript">
    setTimeout( function () { location.href = location.href.split('&')[0]; }, 50000);
</script>

The code above imitates refrash by passing modified href (everything after first & is removed) href of your current location

Upvotes: 0

Related Questions