Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Javascript variable to Rails 3 controller using Jquery

I am using Rails 3, Jquery-UJS and Jquery. I have a working setup of Jquery with Rails3 .I am trying to send a variable from Javascript to Rails controller by clicking a link.

My current approach is using js as follows to make an ajax call and pass msg string.

$("#select_link").click(function() 
{$.ajax({
type: 'POST',
url: 'http://your_url/jmsg',
data: {msg: "hello world"},
;}
});
});

Should I include this code in my application.js file?

In my .html.erb file I have

<%= link_to "Send variable", jmsg_path, :remote => true %>

In my controller I have

def jmsg
@message= params[:msg]
respond_to do |format|
format.js
end
end

Till now, I've not been able to get the javascript variable in my @message instance variable

EDIT:

I made changes as suggested. However, the variable @message is not set when I do

  @message=params[:msg]

When I check XHR using Fiebug, I see 302 Moved Temporarily for the POST action (the POST parameter msg is set correctly though). Response is - $("#show_message").html("")

My .js view is:

 $("#show_message").html("<%= @message %>")

EDIT2 : When I check Firebug, it shows that there are two actions now: 1. POST /jmsg - with response @message = "hello world" 2. GET /jmsg - with response @message= " "

like image 967
Shantanu Bhalerao Avatar asked Sep 28 '26 04:09

Shantanu Bhalerao


1 Answers

When i wanna get any value from controller, i always use json format by doing something like these.

// jmsg.js.erb

{
  "message": "<%= @message %>"
}

// yourjs.js

$.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

$("#select_link").click(function(){
  $.ajax({
    type: 'POST',
    url: 'http://your_url/jmsg',
    dataType: 'json',
    data: {msg: "hello world"},
    success: function(json, status, xhr){
      // $("#show_message").html(json.message)
    }
  });
});

// in your.html.erb, remove :remote => true

<%= link_to "Send variable", jmsg_path %>
like image 143
raymondralibi Avatar answered Sep 29 '26 21:09

raymondralibi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!