Topic: Pulling variables into controller through AJAX call from javascript

I am trying to pull in parameters from javascript into my controller through jQuery AJAX call.  It is currently just an integer that I want to be passed, and for future use how would I add multiple parameters? How do I access the :data field through the controller? Here is my code:
Javascript:
function getScore(fieldClicked) {
    $.ajax({
        url: 'scores',
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
        accept: 'application/json',
        dataType: 'json',
        data: {inputData: fieldClicked},
        //data: '{"@predicate":"' + obj['@predicate'] + '","@type":"' + obj['@type'] + '","@value":"' + obj['@value'] + '"}',
        success: function(res) {
            if (res.ImportResponse !== void 0) {
                console.log('Success: ' + res);
            } else if (res.Fault !== void 0) {
                console.log('Fault: ' + res);
            }
        },
        error: function() {
            console.error('error!!!!');
        }
    });
};

Controller Code to pull the :data field
@dummy = params[:data]

How do I fix this?

Last edited by ChrisL1200 (2012-02-16 15:00:16)

Re: Pulling variables into controller through AJAX call from javascript

Since you want to send to rails,  you should do it the rails way and put it in the url

    $.ajax({
        url: '/scores/' + whatever,
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
     });

Then add a route

get '/scores/:data' => 'foo#scores'

then in foo_controller.rb

def scores
   @jsondata = params[:data]
end

That leaves off a lot of detail,  but you get the idea!

Rails has json support built in,  so at some point you'll have to read up a bit more on it,  but the above approach is making your JavaScript conform to Rails conventions.

Also, remember REST,  if sending that data to rails will create a resource in rails (create a record in a table for example),  it should be a post and not a get.  It will work either way,  just not be true to the RESTful principals encouraged by Rails

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

So if I wanted to send in two integer values instead of JSON I have to do all of that?  Just mainly curious on how I access the :data cause I can see through debugging that my AJAX call is hitting my controller.

Re: Pulling variables into controller through AJAX call from javascript

Well,  now that I re-think it,  if the json you want to send is very long and complex, or maybe contains sensitive data you don't want exposed,  you could do it the way you originally proposed, send it in the data
then you'd have to grab it from the response.body

i.e. leave the javascript as you have it except change the url to '/scores',  forget the new route, then

def scores
  @jsondata = response.body
end

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

Ok when I debug through the controller

def scores
  @jsondata = response.body
end

@jsondata is no longer null it equals "", what exactly is response.body returning?

Re: Pulling variables into controller through AJAX call from javascript

Sorry, I'm having brain farts left and right.

request.body!!!!!

and it's a Ruby IO input stream

i.e.

request.body.read

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

Now I get a StringIO object, how do I convert this back into the data I want?

Re: Pulling variables into controller through AJAX call from javascript

First check out the ruby docs:

http://ruby-doc.org/core-1.9.3/IO.html#method-i-read

request.body.open('r') {|f| @data = f.read }

It depends on how you've structured the data on the java side,  you might have to do this

@alldata = ''
request.body.open('r') do |f|
  while @line = f.read
    @alldata += @line
  end
end

Just depends!

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

NoMethodError in ScoresController#scores

private method `open' called for #<StringIO:0x007fd3ba5d89b0>, this is the result when I use either of the suggestions that you gave.  How would I structure the data in order to get the first one you posted to work?  Sorry for the insane amount of questions

Re: Pulling variables into controller through AJAX call from javascript

Again with the brain farts. 

So sorry,  my fault,  I gave you FileIO instructions,  it's an IOStream,  no need to open it!

@data = request.body.read
or
@alldata
while @line = request.body.read do
  @alldata += @line
end

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

This doesn't seem to be working; just a refresh of where I am at what I am trying to incorporate:  I want to pass two integers up into rails controller from my AJAX call. Here is the code I currently have:

Javascript:
function getScore(fieldClicked) {
    $.ajax({
        url: 'scores',
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
        accept: 'application/json',
        dataType: 'json',
        data: {max:1.0, min: 0.0},
        //data: '{"@predicate":"' + obj['@predicate'] + '","@type":"' + obj['@type'] + '","@value":"' + obj['@value'] + '"}',
        success: function(res) {
            if (res.ImportResponse !== void 0) {
                console.log('Success: ' + res);
            } else if (res.Fault !== void 0) {
                console.log('Fault: ' + res);
            }
        },
        error: function() {
            console.error('error!!!!');
        }
    });
};

Controller:

    @data = request.body.read
    @data.each{|dataElement|
      @maxima = dataElement['max']
      @minima = dataElement['min']
    }

Where I want to store the max into maxima and min into minima.  Now that I am looking at it I guess i do have a JSON object rather than just an integer. Do I have to do a
@data.each{|dataElement|
@maxima = dataElement['max']
@minima = dataElement['min']
}

Thanks for all your help!

Re: Pulling variables into controller through AJAX call from javascript

Try this,  I've never used JSON so it's the blind leading the blind
@data = ActiveSupport::JSON.decode(request.body.read)
@maxima = @data['max']
@minima = @data['min']

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

Figured it out, luckily in the debugger I was able to find what variables the controller had access to and boom found the data.  Here is what I did:

@data = request.filtered_parameters
    if(@data != nil)
      @maxima = @data['max']
      @minima = @data['min']
    end

Thanks for all the help again!

Last edited by ChrisL1200 (2012-02-17 10:31:11)

Re: Pulling variables into controller through AJAX call from javascript

Great

Looks like you could of used just

@data = request.parameters

filtered_parameters will strip out sensitive stuff before logging,  i,e, password

either way,  we both learned something!

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Pulling variables into controller through AJAX call from javascript

Now I am hitting something strange even when using the request.parameters, before I had the input values hardcoded:

function getScore(fieldClicked) {
    $.ajax({
        url: 'scores',
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
        accept: 'application/json',
        dataType: 'json',
        data: {max:1.0, min: 0.0},
        //data: '{"@predicate":"' + obj['@predicate'] + '","@type":"' + obj['@type'] + '","@value":"' + obj['@value'] + '"}',
        success: function(res) {
            if (res.ImportResponse !== void 0) {
                console.log('Success: ' + res);
            } else if (res.Fault !== void 0) {
                console.log('Fault: ' + res);
            }
        },
        error: function() {
            console.error('error!!!!');
        }
    });
};

But I thought I could just pop in my variable then I would be golden however it no longer sees it in request.parameters if I do this: function getScore(fieldClicked) {
    $.ajax({
        url: 'scores',
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
        accept: 'application/json',
        dataType: 'json',
        data: {max:fieldClicked, min: 0.0},
        //data: '{"@predicate":"' + obj['@predicate'] + '","@type":"' + obj['@type'] + '","@value":"' + obj['@value'] + '"}',
        success: function(res) {
            if (res.ImportResponse !== void 0) {
                console.log('Success: ' + res);
            } else if (res.Fault !== void 0) {
                console.log('Fault: ' + res);
            }
        },
        error: function() {
            console.error('error!!!!');
        }
    });
};

The max in the second one is no longer useable when i do this, confused as to why

UPDATE: This was an error on my end, the input variable was undefined so obviously it would be unpassable.

Last edited by ChrisL1200 (2012-02-17 12:11:49)