1

Cannot seems to figure out how I can post a query(json) array to a rails controller#action

I have just like

var myarray = []; ( with values )

My controller action I want to post to:

def process
end

Everywhere I find answers on how to get JSON -> Jquery But Ill need the other way around. Anyone knows how to do this? Can't be that hard?!

1
  • Do you want to post (screen flash, reloads page) or AJAX Post in the background? Commented Oct 7, 2011 at 15:17

2 Answers 2

4

There's probably a few ways to do this, but here's one. Use some JS like this to post to your controller:

var target = "your-action-url";
var myarray = [1,2,3,etc];
$.ajax({
    type: 'get',
    url: target + '?order='+myarray.join(',') ,
    dataType: 'script'
});

Then, in your controller:

data = params[:order].split(',')

Now you have an array that matches what you had in javascript.

Sign up to request clarification or add additional context in comments.

3 Comments

You could easily run into problems with large arrays, since URLs have a character limit
I only post integers and no more than 20 so that will work out, something to look into later on ( if anyone has suggestion to fix that its more then welcome ). Had some 500 server error cause I forgot to create the view file! all seems to work great now thx!
you could always POST instead of GET to take care of the URL size issue. I haven't actually hit the URL character limit issue in over a decade personally, although it is worth being aware of it.
2

The jQuery documentation has information about posting: jQuery.post()

Does something like this help? $.post('path-to-process-action', {myarray: myarray})

2 Comments

This is good, but you instead of just passing the array as the data argument you should use a map like $.post('path-to-process-action', {myarray: myarray})
Edited answer to use the map version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.