[Rails] Re: Headache with Ajax in Rails using jQuery
what's kind of error you met? did you use firebug to trace? It is better to use remote-form of rails. http://www.alfajango.com/blog/rails-3-remote-links-and-forms/ is valuable to be read if you want to use rails-ujs way.
On Tuesday, May 28, 2013 7:23:00 AM UTC+8, Ruby-Forum.com User wrote:
Hello everyone, I'm a newbie at Ruby on Rails. I spent nearly two days--
of the Memorial Day weekend stumbling upon making Ajax working in Rails.
At this point, I'm so exhausted and hope that I can get some help to
move forward. I have tried nearly everything I found on Google but
still not successful. Initially, I tried the Ajax approach offered by
Rails but did not work, so I turned to jQuery for Ajax. Basically, I
want to submit a form using Ajax:
<%= form_tag("/main/contact", :method => "post", :id => "contactForm")
do %>
Name: <%= text_field_tag(:name) %><br/>
Message: <%= text_area_tag(:message) %>
<%= submit_tag "Send" %>
<% end %>
<div id="result"></div>
And here's my Ajax code in jQuery:
<script type="text/javascript">
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* clear result div */
$("#result").html('');
/* get values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "/main/contact",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html(data);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
});
</script>
And here's my main controller:
def contact
name = params[:name]
message = params[:message]
respond_to do |format|
format.html # contact.html.erb
format.json {
render :data => {:name => name, :message => message}
}
end
end
At this point, I just want to test to see if user's name and message can
be submitted successfully via Ajax, and if so, insert the submitted
values (name & message) in the <div id="result"></div>. Would you
please look through and let me know where I did wrong. I appreciate any
help. Thanks a lot.
--
Posted via http://www.ruby-forum.com/.
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/f01ab19c-d46b-4395-a614-e5fff1c4e5d2%40googlegroups.com?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home