16

I want to be able to produce a URL based on certain properties and then go to the new URL in javascript.

Here is what I have so far:

triggerNumber = document.findcontrol(txtTrigNo).text;
hostAddress= top.location.host.toString();      
url = "http://" + hostAddress "/" + triggerNumber

How do I navigate to the new URL?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Mike James
  • 461
  • 2
  • 4
  • 20

3 Answers3

29

Simply try:

window.location = url;

But before trying to do that, you have to make sure the page at the address "http://" + hostAddress "/" + triggerNumber exists. For example by putting valid triggerNumbers in an array and check if it exists or not. So:

//Not sure if at the end it should be .text or .value or .value()
triggerNumber = document.findcontrol(txtTrigNo).text;
var validTriggers = [123, 456, 789];
if (validTriggers.indexOf(parseInt(triggerNumber)) == -1) {
    alert("Invalid trigger number");
} else {
    hostAddress= top.location.host.toString();        
    url = "http://" + hostAddress "/" + triggerNumber;
}

Finally, if the destination is a server-side page (php, asp, etc), the address usually looks like this:

"http://" + hostAddress "/trigger.php?id=" + triggerNumber;

but you'd better use forms for this.

Edit: As Cerbrus suggested, validating the values with javascript is a good way to tell the user about his errors before navigating away from the page. But to make sure the correct data is sent to server, it is important to do the validation in the server-side code, too.

In this example, in case of an invalid trigger number the user may finally see a 404 error; but with sensitive information worse things can happen.

Hossein
  • 4,097
  • 2
  • 24
  • 46
  • For what it's worth, I'd suggest first and foremost to validate the trigger numbers server-side. – Cerbrus Dec 27 '12 at 10:28
  • @Cerbrus: Thanks. Actually for OP's specific question, there isn't much to check before sending the data, as it is only address concatenation. The destination page must take care. Anyway I added some information about this. – Hossein Dec 29 '12 at 12:34
5

What you need is:

document.location.href = url;

After you have the URL in the url variable.

To get value of input element have:

var triggerNumber = document.getElementById("txtTrigNo").value;
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

This will get the hostname and port of the server, and concatenate the value of the element onto the end, and then go to the resulting URL.

var triggerNumber = document.getElementById("txtTrigNo").value();
var url = "http://"+window.location.host+"/"+triggerNumber;
window.location = url;
Rob Grant
  • 7,239
  • 4
  • 41
  • 61