aborted
aborted

Reputation: 4541

Generating my website's URL in Javascript

I have this function that is in charge of generating HTTP URLs for the current environment I'm on. When I'm working on my localhost, the function returns something like:

http://localhost/mysite

While on production it's supposed to return my website's domain only, like:

http://mywebsite.org

This is not the case all the time. This function works partially and I can't understand why. I use this function to submit AJAX forms to PHP scripts around my website and it works, however, when I try and use this function to redirect an user to a specific location which SHOULD include the full HTTP URL, then it sends me to the localhost URL.

Here's the function I've written:

function generate_site_url()
{
    var domain = window.location.origin;
    if (domain.indexOf('localhost'))
    {
        return 'http://localhost/mysite/';
    }
    else
    {
        return 'http://mywebsite.org/';
    }
}

And this is the redirect function that's causing trouble with the wrong redirecting:

function redirect(to, mode, delay, internal)
{
    mode     = (typeof mode === "undefined") ? 'instant' : 'header';
    delay    = (typeof delay === "undefined" || delay === null) ? 0 : delay;
    internal = (typeof internal === "undefined" || internal === true) ? true : false;

    if (to)
    {
        to = ((internal) ? generate_site_url() : '') + to;      
    }
    else
    {
        to = currentLocation(); 
    }

    setTimeout(function(){
        window.location = to;
    }, delay);
}

And this is an example usage of redirect that's causing trouble:

redirect('admin/index', 'header', 3000);

The function call above is sending me to http://localhost/mysite/admin/index even though I'm in production and my domain case should apply.

What's wrong with it? I can't seem to be able to figure it out.

Upvotes: 0

Views: 41

Answers (1)

clyfish
clyfish

Reputation: 10450

Change

if (domain.indexOf('localhost'))

To

if (domain.indexOf('localhost') != -1)

Or

if (~domain.indexOf('localhost'))

Upvotes: 2

Related Questions