Wednesday, 16 January 2019

javascript - Executing a js file returned inside an ajax response



I have a HTML5 application which is using jquery 3.2.1.




In part of the application - a search feature - I make an ajax request. The response from the ajax request is HTML, and this includes a . That is where the problematic js is located and the full contents of that are shown above in this question - the bit that includes console.log('search_regulations.js firing')



Answer



One of the problems that I see is that you're binding the onclick to the same elements multiple times...



Since the js can be loaded multiply times via ajax requests, it is important to first detach, before attaching again events.



The other problem, is that you're running the code in $(document).ready event (that is when HTML-Document is loaded and DOM is ready), however you'd probably be better off to run the code in the $(window).load event (which executes a bit latter, when complete page is fully loaded, including all frames, objects and images)



Example:



$(window).load(function() {  


console.log('search_regulations.js firing');

//off: detach the events
//on: attach the events
$('.browse-ctp__filters-data .include, .exclude').off('click').on('click', function(){
...
}
});


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...