3

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= " "

3 Answers 3

1

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 %>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! data : {msg: "hello world"} gives POST with msg parameter and value "hello world" (checked it in Firebug). I am still not able to set the variable @ message though (edited my question above with more info)
Thanks! The Json data is being received with the POST /jmsg (checked with Firebug). However, the @message variable is not persisted because I get a GET /jmsg due to redirect html option in my controller. (stateless controller). How can I avoid this? (I realize that saving in database is a solution)
AFAIK, redirect html option in controller only render the target view. Redirect won't process any code in target action inside controller. For example, you declare @message = "something" inside action jmsg. Inside action another_action in the same controller you put redirect_to :action => "jmsg". You will never get @message on jmsg.js.erb unless you declare @message = "something" inside another_action.
I removed the redirect. Added more information as Edit 2 - I still get both POST and GET actions.
0

Add the below code into your application js and try this

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

});

3 Comments

Thanks for your reply and help. I am still not able to set the @ message instance variable and I don't see anything in my .js view. I edited my question to add more info.
Where are you putting this line $("#show_message").html("<%= @message %>")?
That line is my format.js file (jmsg.js). Please refer to my controller code. I get POST /jmsg first and then the format.js is executed and redirected by GET /jmsg. So the @message variable is not persisted.
0

Okay, I will share with you what I know about using AJAX and jQuery in Rails, in an unobtrusive manner:

First, include this at the beginning of your application.js file

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

Then, in the same file, create a function as follows, with is the function that loads before the DOM loads. In this function, you write your own functions:

$(function() {
   $("#select_link").sendVar();
}

jQuery.fn.sendVar = function(){
    this.click( function() {
    var msg= 'hello world';
       $.post('/your_url/jmsg/' + msg, function(data){

        })
       return false;
    });
}

Make sure you have a route for this post request in your routes.config file, for e.g.

match 'your_url/jmsg/:msg', :controller => 'your_url', :action => 'jmsg', :via => :post

Let me know if this works for you. A similar code worked for me, for a similar case. Thanks.

2 Comments

Thanks for the reply. Your code is doing POST action and sending msg variable. I'm doing something similar. There seems to be some other issue. Since the controller is stateless, maybe @message = params[:msg] is not valid?
params[:msg] is perfectly valid. Your code is doing a POST as well. Did you try my code? all of it, including having the route in routes.rb file. This should work.

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.