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.