I'm new to rails (coming from PHP) and am having an issues with submitting a form with ajax. Basically, I have a list of tasks, and when a new one is added I want the new task to append to the list. The form itself is submitting, but I can't figure out how to append the new entry. Thanks in advance!
THE FORM
<%= simple_form_for(Task.new) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :date_due %>
<%= f.input :phase_id, :as => :hidden, :input_html => { :value => @phase.id } %>
<%= f.input :status, :as => :hidden, :input_html => { :value => "0" } %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
THE JS
$('form#new_task').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON"
}).success(function(data){
// disaply new charge in the table
$('body').append(data);
// clear the form
$("input#task_name").val('');
//focus on the input again
$("input#task_name").focus();
});
return false; // prevents normal behaviour
});
EDIT It's also worth mentioning that this is happening inside a view for a "Phase". Each phase has_many tasks and each task belongs_to a phase.
It looks like JSON is being returned from the controller. You need to wrap the returned JSON in html, same syntax as the other rows in the table you want to append to ( maybe <tr><td>..</td></tr>
) then append that html to the table. Or you could make a partial for each row in your table, and when you add a new task, return the html of the partial from the controller and then append that to the table.
<table id="tasks">
<% @phase.tasks.each do |task| %>
<%= render :partial => 'task_row', :locals => {:task => task} %>
<% end %>
</table>
Change js to:
$('form#new_task').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "HTML"
}).success(function(data){
// disaply new charge in the table
$('#tasks').append(data);
// clear the form
$("input#task_name").val('');
//focus on the input again
$("input#task_name").focus();
});
return false; // prevents normal behaviour
});
And in your controller something like this
def create
@task = Task.new(params[:task])
respond_to do |format|
if @task.save
format.js{render :partial => 'tasks', :locals => {:task > @task} }
else
#handle validation error
end
end
end
This all complete untested but I hope it gets you on the right track