passing parameters to rails back end from an ajax call

- 1 answer

Ad

I am trying to pass an API route to rails for the server to perform the call instead of the client. I get a 404 not found when I try to do this. From the console it works find when I am passing this route to the method. However not from the ajax call. Here is my controller method:

    def identification
       @link = params[:link]
       @response = MotorClient.new.response_from_path(@link)
       render json: @response
    end

Here is my route:

    get '/identification/:link', to: 'vehicles#identification', on: :collection

Here is my ajax:

    handleRoute: function (e) {
    this.handleChange(e);
    e.preventDefault();
    var options = e.target.options;
    var route = "";
    for (var i = 0, l = options.length; i < l; i++) {
        if (options[i].selected) {
            route = (options[i].dataset.route);
            console.log(route)
            $.ajax({
                type: 'get',
                url: '/vehicles/identification/',
                dataType: 'json',
                data: {"link":encodeURIComponent(route)},
                success: function (data) {
                    this.props.getMakes(data);
                }.bind(this),
            })
        }
    }
},

When I console.log the route I get the correct string like this "/v1/Information/YMME/Years/2012/Makes/56/Models" and Like I said from the rails console it works but I can't get the parameter correctly this is what I get on the javascript console when I do thru the ajax call:

     GET http://localhost:3000/vehicles/identification/?link=%252Fv1%252FInformation%252FYMME%252FYears%252F2012%252FMakes 404 (Not Found)

What am I doing wrong?

Ad

Answer

Ad

Looks like your route is expecting the link to be a segment in the URL path instead of a query string variable: /identification/:link -- Try dropping the /:link or appending the encoded link at the end of your URL when making an AJAX call back to the server.

Ad
source: stackoverflow.com
Ad