Mike James
Mike James

Reputation: 471

Create and go to url with Javascript

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?

Upvotes: 16

Views: 78667

Answers (3)

Hossein
Hossein

Reputation: 4137

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.

Upvotes: 29

Rob Grant
Rob Grant

Reputation: 7348

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;

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

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;

Upvotes: 5

Related Questions