Reputation: 1223
On getData() I use an ajax get request to pull a few li and append them to the container. On the success of the ajax call I make a variable called next_load which gets the data-attribute and passes it as the url for the next get data call. The problem I have is that on the second click there is a build up of variable on the call. In the console I can see the first date being passed with the second date as well. The goal is on page load to get the first dates. Then clicking on the box to get the next dates and so on.
HTML:
<div id = "calendar">
<div class = "box">
<ul class = "label">
<li>Sun</li>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thur</li>
<li>Fri</li>
<li>Sat</li>
</ul>
</div>
<ul class = "box-content">
</ul>
</div>
in console:
2 calendar.js:34 2016-03-05 -> on the first get, then this and the next on the second get and it keeps building up.
calendar.js:34 2016-04-09
function getData(url) {
var next_load = '';
$.ajax({
url: 'student/calendar/' + url,
type: 'GET',
success: function(response) {
var $result = $(response).filter('li');
$('.box-content').append($result);
next_load = $result.last().attr('data-date');
useNextLoad(next_load); // dont use the value till the ajax promise resolves here
}
})
}
getData('show/2016/02');
function useNextLoad(next_load){
var load = next_load;
$('.box').click(function(){
getData('load/' + load);
console.log(load); // when i pass the next_load Im getting the previous next load and the new next load at the same time. Then on the next click the amount compounds.
});
}
If I reset the variable next_load would that keep the build up from occuring? I tried to empty the variable before the ajax call but I still get the build up.
Upvotes: 0
Views: 113
Reputation: 703
Might be an issue with the click function being multiply applied to .box. You may want to remove any existing click handler from .box before binding a new one. See How to remove all Click event handlers in Jquery
function useNextLoad(next_load){
var load = next_load;
$('.box').off("click"); // Remove any click handlers already on .box
$('.box').click(function(){
...
Of course, you can also chain your calls in jQuery if you want to be more compact.
Upvotes: 1