1

How would I go about sending a PUT request to an action through javascript in Rails? Here's how I do it in the .html.erb file:

<%= link_to "Check", check_task_path(task), :method => :put %>

How would I do this in javascript?

1 Answer 1

1

Add :remote => true to enable ajax on the link.

<%= link_to "Check", check_task_path(task), :method => :put, :remote => true %>

Assuming you want a check tasks in index page.

index.html.erb

<table>
  <tr>
    <th>Name</th>
    <th>Completed</th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @tasks.each do |task| %>
  <tr>
    <td><%= task.name %></td>
    <td id="completed_<%= task.id %>"><%= task.completed %></td>
    <td><%= link_to 'Show', task %></td>
    <td><%= link_to 'Edit', edit_task_path(task) %></td>
    <td><%= link_to 'Destroy', task, :confirm => 'Are you sure?', 
            :method => :delete %></td>
    <td><%= link_to "Check", check_task_path(task), :method => :put, 
            :remote => true, :class => :check_task %></td>
  </tr>
<% end %>
</table>

tasks_controller.rb

  def check
    @task = Task.find(params[:id])
    @task.completed = true
    respond_to do |format|
      if @task.update_attributes(params[:task])
        format.html { redirect_to(@task, 
         :notice => 'Task was successfully updated.') }
        format.xml  { head :ok }
        format.js  
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @task.errors, 
           :status => :unprocessable_entity }
        format.js
      end
    end

check.erb.js

<% if @task.errors.empty? %>
  jQuery("#completed_<%= @task.id %>").html("true.");    
<% else %>
  alert("Task could not be saved.");
<% end %>

routes.rb

  resources :tasks do
    member do
      put 'check'
    end
  end

application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Tada</title>
  <%= stylesheet_link_tag :all %>
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" %>
  <%= javascript_include_tag :defaults %>

  <%= csrf_meta_tag %>

</head>
<body>

<%= yield %>

</body>
</html>
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, well how do I send any (POST or GET) request to a controller action with javascript?
Ok, but I'm trying to do it just in javascript, when the user clicks a checkbox (Hence the check function for a task). How do I do that?

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.