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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

For what it's worth, I'd suggest first and foremost to validate the trigger numbers server-side.
@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.
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;

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.