简体   繁体   中英

Ruby on Rails:Can not call ajax callback from form_tag

In my view (/app/view/media/index.html.erb) , i have an ajax function and a form_tags: My AJAX function:

 <script type="text/javascript" charset="utf-8"> $(document).ready( function () { $("#my_ajax").bind("ajax:success", function (evt, data, status, xhr) { console.log(data); } ).bind("ajax:error", function (evt, data, status, xhr) { console.log("doh!") }); }); </script> 
. And my form_tags:
<%= form_tag '/delete_media', method: :delete do %> <%= submit_tag 'Delete', class: 'btn btn-danger', disabled:@media_contents.empty? , :remote => true, :id => "my_ajax" %>

Our goal : when i get response from server after submit, my_ajax function will be run.
How to do it ??? I can not trigger "my_ajax" function ? I always get JSON response from server

EDIT :

My controller :

def delete_media @medias=Media.where(id: params[:media_contents]).destroy_all render json: @medias end

maybe try something like this:

<script>
  $(document).ready(function(){
    $("#my_ajax").on('ajax:success', function(e, data, status, xhr){
      console.log(data);
    }).on('ajax:error',function(e, xhr, status, error){
      console.log('doh!')
    });
  });
</script>

You should not write js handle ajax like that.
Properly way to implement ajax in rails is:

In /app/view/media/index.html.erb:

form_tag ..., remote: true

In media Controller:

def destroy
    # do your job
    respond_to do |format|
      format.js   {}
    end
end

In /app/view/media/destroy.js.erb:

// your js handle code

More information: http://guides.rubyonrails.org/working_with_javascript_in_rails.html

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