Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and go to url with Javascript

Tags:

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?

like image 536
Mike James Avatar asked Mar 24 '11 11:03

Mike James


People also ask

How do I get the URL of a website using JavaScript?

If you're using JavaScript in the browser you can get the full current URL by using window. location. href .

How do I navigate to a URL?

To navigate to a new URL, use the location object from the Browser's History API. The session history lets you reassign the location object to a new URL or use the href property on that same object. The syntax for this approach is: window.

How JavaScript is used in URL?

In JavaScript, the URL interface is used to parse, construct, normalize, and encode URLs. It provides static methods and properties to read and modify different components of the URL.


1 Answers

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.

like image 148
Hossein Avatar answered Sep 24 '22 17:09

Hossein