简体   繁体   中英

Javascript function reference error

I am trying to call a Javascript function through a command button on my Rails app.

function fetchpurchases() {
  var startDate = $('#histStart').val();
  var endDate = $('#histEnd').val();
  $('#histMainFrame').empty();
  $.ajax({
    url: '/transHistory/confirm?start_date=' + startDate + '&end_date=' + endDate,
    type: 'get',
    beforeSend: function() {
      $('#mainContDiv').append('<img id=\'spinner\' src=\'/assets/spinner_green.gif\'>');
    },
    success: function(output) {
      $('#spinner').remove();
      $('#histMainFrame').html(output);
      $('#transPurTab').DataTable({
        destroy: true,
        lengthChange: false,
        pageLength: 50,
        paging: true,
        stripeClasses: ['oddStrip','evenStrip']
      });
    }
  });
}

A button is defined with the onclick event calling the Javascript function.

<div id="histToolbar">
  <div id="errorDiv"><p class="bigRedBright"></p></div>
  <table id="histTools">
    <tr>
      <th>Start Date</th>
      <th>End Date</th>
      <th></th>
    </tr>
    <tr>
        <td><input type="text" class="datepicker" id="histStart" placeholder="Start Date..."></td>
        <td><input type="text" class="datepicker" id="histEnd" placeholder="End Date..."></td>
        <td><button onclick="fetchHistory()" id="histSubmit">Submit</button></td>
        <td><button onclick="fetchpurchases()" id="deliverSubmit">Confirm Delivery</button></td>
    </tr>
  </table>
</div>

I can navigate to the page I created by typing it manually into the browser. The MySQL query I wrote works correctly, but when I try to navigate using the button, I get reference error: fetchpurchases is not defined .

Additionally (may not be related), the function does not show up in the DOM window when I try to debug the error using Firebug.

I would do something like so

// Create a namespace for your code
var App = App || {};

(function() {
  App.fetchpurchases = function() {
    //Your code here
  };
})();

If you don't want to use JS or jQuery to bind the function to an event you can change your HTML to:

<td><button onclick="App.fetchpurchases()" id="deliverSubmit" type="button">Confirm Delivery</button></td>

Of course wherever you place that javascript needs to be added to application.js or loaded into the page manually.

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