简体   繁体   中英

Ajax post submit form ruby on rails

Where actually I can get my variable pass to my js.erb, let say

I have 1 method create,in controller in my application.js, i have my Ajax post then I have my create.js.erb

In my create form, I have 2 hidden_field_tag In my create.js.erb , this is here where the ajax success post and do the action, but how do I access the hidden_field data to carry out my logic to perform certain action when success?

This is due to, when it's js success, I got 2 different action to determine which action I should process. How actually js.erb works? Besides, when I alert the form data in application.js, it dont come out the alert although the js is working perfectly. Any idea?

$(document).ready(function() {
  $("#new_answer").submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    alert("you are submitting" + $(this).serialize()); //it dint work but it did post
    return false;
  })
})

Wait, when you do this, lets say your :controller => "months" and :action => "march".

I mean your $(this).action() returns "/months/march".

This will stored in url and when you hit that url by the below post method, the form elements are available in the "march" action of the "months" controller in the params hash.

Now, in the "result" js variable, the whole params hash will be available, which is actually you are alerting.

months_controller.rb

def march

  render :text => params

end

application.js

$("form#new_answer").submit(function() {  

          var data = $('form#new_answer').serialize();

          var url = $(this).action();

           $.post(url ,data, function(result){

            alert(result);

            });        

           return false;

          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM