Reputation: 3034
Alright, I'm pretty close on this, but I need a bit of help getting over the hump. I'm trying to submit a form via AJAX, in a rails app, which sends an email, and then executes some code on success. When I hit enter on my form, the AJAX is working, because I'm getting the email. However, the success code isn't running (nor the error for that matter). I also tried 'complete:' but that didn't work, so I suspect it may be some problem with the default form behavior? Ideas?
Here is the ajax:
// AJAX Function to submit email form without refreshing page
$("#contact_me").submit(function(){
var dataSet = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: dataSet,
success: function(){
alert("Sent!");
},
error: function(){
alert("Something went wrong!");
}
});
return false;
})
And the rails action which it calls:
def email_me
name = params[:name]
email = params[:email]
content = params[:text]
ContactMailer.first_contact(name, email, content).deliver
head :ok
end
Also, the form itself
<%= form_tag({controller: "main", action: "email_me"}, id: "contact_me", remote: "true") do %>
<div>
<p><%= label_tag(:name, "Name") %>
<%= text_field_tag(:name) %></p>
</div>
<div>
<p><%= label_tag(:email, "Email") %>
<%= email_field(:user, :email) %></p>
</div>
<div>
<p><%= label_tag(:text, "What's on your mind?") %></p>
<%= text_area_tag(:text)%>
</div>
<%= submit_tag("Say Hello!")%>
<% end %>
Upvotes: 2
Views: 2208
Reputation: 3034
It's really the little things that end up causing the biggest problems. I forgot to wrap the whole function in a function(){..}. Go figure, works great now. Thanks for the help all.
$(function(){
$("#contact_me").submit(function(){
var dataSet = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: dataSet,
complete: function(){
alert("Sent!");
},
error: function(){
alert("Something went wrong!");
}
});
return false;
});
})
Upvotes: 2
Reputation: 637
Try rendering blank json instead, as your JS is expecting a JSON response.
render :json => {}
Upvotes: 0
Reputation: 575
Your rails app should return JSON. You are ajaxing a JSON request, it should be a JSON response. I hope this helps.
Upvotes: 0
Reputation: 6689
Completely random guess so forgive me if it's ridiculous, could it be render :nothing => true
preventing Rails to fire the callback?
Upvotes: 0