简体   繁体   中英

How to make ajax request work on page load

I have an ajax request that updates a piece of text on the screen when a dropdown input is selected using 'onchange'. However i want the same behaviour to happen on page load as well but i cant seem to find the correct syntax.

 $(document).on('change','#standalone-invoice-billpayer', function (evt) { updateCardDetailsText(evt) });

So above, i click on the dropdown called 'standalone-invoice-billpayer' and then execute the function which contains the ajax request which works perfectly. But i want the same thing for on page load. I am using Ruby on Rails. Thanks for any help

If you are using Turbolinks you will need to add an event listener for the turbolinks:load event. If you just add a listener for the jQuery.ready event it will only be fired once on the initial page load and not when the page is replaced by turbolinks.

Turbolinks triggers a series of events during navigation. The most significant of these is the turbolinks:load event, which fires once on the initial page load, and again after every Turbolinks visit.
- https://github.com/turbolinks/turbolinks#observing-navigation-events

document.addEventListener("turbolinks:load", function(evt) {
  updateCardDetailsText(evt);
});

If you are not using turbolinks you can just fire it with jQuery.ready :

// shorthand for jQuery.ready(function(){ ... });
$(function(){
  updateCardDetailsText(evt);
});

You can also just fire the ajax call as soon as the script is loaded and then modify the DOM as soon as its ready to be manipulated:

jQuery.getJSON('/foo.json').done(function(data){
  $(function(){
    modify_the_dom_with(data);
  });
});

This can be an important optimization if you have elements that are populated via ajax as they will appear to be much snappier.

Trigger the change event on the element in the code:

$(function() {
    $(document).on('change','#standalone-invoice-billpayer', function (evt) {
       updateCardDetailsText(evt)
    });
    $("#standalone-invoice-billpayer").change();
});

The call to .change() will cause the event handler to run, and it will then call updateCardDetailsText() .

proper triggering is like this, however the evt value will just get whatever default value you have in the element "#standalone-invoice-billpayer"

$(document).on("turbolinks:load",function() {

 $("#standalone-invoice-billpayer").trigger('change');

});

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