Algorithmic Programmer
Algorithmic Programmer

Reputation: 766

How can I access Rails Routes/URLs in my JavaScript?

I'm painfully new to Ruby on Rails, so bear with me here.

So, I just created the following URLs for my web application:

HOMEPAGE (WHEN RUNNING PROJECT LOCALLY): localhost:3000
PRODUCTS PAGE: localhost:3000/products
TOYOTA PAGE: localhost:3000/products/toyota
HONDA PAGE: localhost:3000/products/honda
FORD PAGE: localhost:3000/products/ford
NISSAN PAGE: localhost:3000/products/nissan
CHEVROLET PAGE: localhost:3000/products/chevrolet
MERCEDES PAGE:  localhost:3000/products/mercedes
BMW PAGE: localhost:3000/products/bmw
HYUNDAI PAGE: localhost:3000/products/hyundai

Here's my config/routes.rb where I'm creating these URLs:

get 'products', to: 'static#products'
root to: 'static#home'

get 'products/toyota', to: 'static##products#toyota'
get 'products/honda', to: 'static#products#honda'
get 'products/ford', to: 'static#products#ford'
get 'products/nissan', to: 'static#products#nissan'
get 'products/chevrolet', to: 'static#products#chevrolet'
get 'products/mercedes', to: 'static#products#mercedes'
get 'products/bmw', to: 'static#products#bmw'
get 'products/hyundai', to: 'static#products#hyundai'

And here's a snippet of the JavaScript file for my products page:

    g.prototype.Ce = function(b,
        f) {

        var e = this;
        x.i.Mg(b, f);
        x.A("build/getModelOptions", {
            year: b,
            make: f,
            included_body_styles: x.options.included_body_styles
        }, function(b) {
            b = a.parseJSON(b);
            e.bg.render(b, function(b) {
                //$("#builder-make-selection .custom_dd_select a").text("Toyota");
                a("#builder_splash_models").html(b);
                a.each(a(".builder_body_types"), function(a, b) {
                    k(b);
                    console.log("b=" + JSON.stringify(b));
                    console.log("k(b)=" + JSON.stringify(k(b)));
                })
            })
        })
    };

Basically, what I want to do is, in the JS, in the line that reads

       make: f;

if I go to the Toyota page: I want to make that line to read:

      make: 'Toyota';

and if I go to the Honda page, I want that line to read:

      make: 'Honda'

and if I go to the Ford page, I want to make that line read:

      make: 'Ford';

And so on and so forth. You get the idea. Any ideas on how to do that?

Upvotes: 0

Views: 135

Answers (1)

Rokibul Hasan
Rokibul Hasan

Reputation: 4156

I think Rails should not be considered to get the current url in JavaScript. You can get current url using following JavaScript code easily

URL       -> document.location;
Path Name -> window.location.pathname;
Full URL  -> window.location.href;

Upvotes: 1

Related Questions