Gonçalo Amaral Gonçalo Amaral -4 years ago 160
Ruby Question

Creating params hash via ajax post method

So i want to create a custom params hash, but im not sure how to do it. I crated a ruby hash(kinda). I had no other ideas

$("#bt-dw , #bt-up").click(function (event) {
var id = $(this).parent().attr("value");
var up = $(this).attr("value");

type: "POST",
url: "/vote",
data: "{:entry_id => '" + id + "',:up => '" + up + "'}",
success: function () {
console.log("post successful");
error: function () {
console.log("post unsuccessful");

the post controller

post '/vote' do
@entry = Entry.get!(params[:entry_id]) rescue halt(404)
@entry.vote(request.ip, params[:up] != 'false')

Answer Source

So from your comment it looks like you are just creating a single-level params hash.

It would be a little more complicated if you wanted to send an array or hash as a param value.

There are two ways to go about this.

Option 1: use this value for data in the ajax request

data: { entry_id: id, up: up }

Option 2: include the same information in the url instead of in data:

url: `/vote?entry_id=${id}&up=${up}`

Note that I'm using ES6 template strings here; this is equivalent to:

url: ( "/vote?entry_id=" + id + "&up=" + up )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download