I am attempting to add an ajax function to a third-party javaScript code. The function is working… but too well… or at least too many times. My research and troubleshooting has led me to determine that the ajax "script" (function) is loading too many times.
I am not a javaScript programmer; though more and more I find the need to use ajax functions within my current code solutions. My solution is — obviously — to become a javaScript programmer. However, I am having some trouble grasping function context, and it has led to the issue I describe above.
Please tell me where/how to position this function so that it loads only for the current instance of the user's content. I know that I am close.
All of the existing answers to questions on this topic involve methods that have been deprecated in the jQuery codex: unbind
, die
, live
, etc... I am using the on
method and thus I am hoping for a more up-to-date answer.
Here is a summary of the content, :
(function ($) {
/* initialize */
var content = function(obj, settings) {
/* populate content */
var populate_content = function(el){
var el_index = instance_vars.elem_index;
if(content_curr_opts.download) {
if(el.download) {
$('.content_download').show();
$('.content_download').on('click' , function(){ // AJAX query:
// for some reason, this is being fired for EACH content image that has been loaded:
// this is because it is LOADED every time the content image is changed
// when this button is clicked, the multiple instances (of this ajax function) all fire at once
var datumA = datum1NeededForAjaxFunction;
var datumB = datum2NeededForAjaxFunction;
$.ajax({ // POST to server using $.ajax:
url: '/ajaxScripts/foobar.php',
type: 'POST',
dataType: 'json',
data: {
'dlLink': datumA,
'dlName': datumB
},
success: function(data){
// do the success things
}
});
});
} else {
$('.content_download').hide();
}
}
};
};
})(jQuery);
jQuery is, of course, active.
Please let me know if there is any other info that I might provide.
Thanks in advance.