ceth
ceth

Reputation: 45295

Simple AJAX example

I have a controller:

class QuestionsController < ApplicationController
  def hello
    puts "====================!!!==================="
    @hello = "hey"
    "some"
  end

  def test
  end

test.rhtml:

<%= javascript_include_tag :defaults %>

<br/>
Click this link to show the current 
<br/>

<%= link_to "hello", 
    { :controller => "questions", :action => "hello" },
    :update => 'time_div', 
    :remote => true %>.

<br/>
<div id='time_div'>
  ...
</div>

When I click on 'hello' link I see that hello() method was called, but html page remains the same. Why?

How do I need to change code to update HTML page?

Here is generated HTML page:

<!DOCTYPE html>
<html>
<head>
  <title>Stack</title>


  <script src="/javascripts/jquery.js?1286229922" type="text/javascript"></script>
<script src="/javascripts/jquery-ujs.js?1286229922" type="text/javascript"></script>
  <meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="UKPX1dNCZhyTk8u71hR9KaUmufIire7Rhvg8t7cRSlM="/>

</head>

<body>



<br/>
Click this link to show the current 
<br/>

<a href="/questions/hello" data-remote="true">hello</a>
<br/>

<div id='time_div'>
  ...
</div>



</body>
</html>

Upvotes: 2

Views: 11253

Answers (2)

Ashish
Ashish

Reputation: 5791

You can have your hello action like this:

def hello
  #### your code goes here #####
  respond_to do |format|
    format.js { render :layout=>false }
  end
end

And one file hello.js.erb

$("#time_div").html("some text");

And your link will be:

<%= link_to "hello", { :controller => "questions", :action => "hello" }, :remote => true %>.

Upvotes: 4

sameera207
sameera207

Reputation: 16629

problem here is you are not returning anything from the controller action, Since you are using AJAX you need to return the result as either .js or jason

have a look at this example, with rails3 and Jquery

https://github.com/nu7hatch/rails3-ujs-example

cheers

sameera

Upvotes: 3

Related Questions