简体   繁体   中英

Page keeps reloading with AJAX call in Ruby on Rails App

I am sure this is a simple solution but it's driving me crazy. I have a Ruby on Rails app whereby I am making a simple AJAX call to a controller action on a jQuery button click event to submit data and initiate a modal pop-up when it successfully submits. See code below.

<script type="text/javascript">
$('.linkclass').click(function() {
  id = $(this).attr('id');
  event.preventDefault();
  $.ajax({
  url: "/controller_name/action_name/" + id,
  type: "GET",
  success: function (data) { 
      // call my modal pop-up
      $( "#dialog" ).dialog();
  }
  });
});
</script>

The only HTML that is relevant in the view for this issue is below (the modal div and the link HTML). Again, this works fine when the Javascript is in the view:

<%= link_to "Submit your info", "/controller_name_name/action_name/#{product.id}", :id => product.id, :class => "linkclass" %>

<div id="dialog" title="Basic dialog" style="display:none">
<p>Your data has been successfully submitted!</p>
</div>

This code works perfectly when the Javascript is in the view and the page does not reload, as I want. However, when I place this Javascript code (minus the script tags) in a separate Javascript file, it refreshes the page when the link is clicked. Everything submits fine but the page reloads/refreshes and I don't want it to reload. Am I forgetting to add something extra to the code when I put it in a separate file? The separate js file is in the assets/javascript folder and is included in the HTML (I see it in view source) so that's not the problem.

Any advice would be appreciated.

The DOM hasn't fully loaded at the time you bind the event handler. You will have to make sure the DOM has loaded before you bind it like so:

$(document).ready(function(){
    $('.linkclass').click(function() {
      id = $(this).attr('id');
      event.preventDefault();
      $.ajax({
      url: "/controller_name/action_name/" + id,
      type: "GET",
      success: function (data) { 
          // call my modal pop-up
          $( "#dialog" ).dialog();
      }
      });
    });
});

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