1

Ok I will try to make it simple.

1) I have 3 links that execute an Ajax Request and update a div with some content.

The DIV

<div id="content-to-update"></div>

The 3 links that update #content-to-update

<a href="#" onClick="executeSomeAjax(CODE=EXAMPLE_1)">example 1</a>
<a href="#" onClick="executeSomeAjax(CODE=EXAMPLE_2)">example 2</a>
<a href="#" onClick="executeSomeAjax(CODE=EXAMPLE_3)">example 3</a>

Each link update the div #content-to-update with the content just below with one parameter named CODE

The the div #content-to-update is updated with the code below.

    var loading = false;
    $(window).scroll(function () {
        var winTop = $(window).scrollTop();
        var docHeight = $(document).height();
        var winHeight = $(window).height();

        //if user reach bottom of the page
        if  (!loading && (winTop / (docHeight - winHeight)) > 0.95) {
            loading = true;


            //the CODE parameter is different on each call from the links that I
            //talked earlier. 
            $.get("/items/next/?list_name=" + CODE,  function(data){

            //executing some javascript to display next items  

            }).done(function() {
                 loading = false;
            })
        }
    });
});

The problem is that it seams the browser keep all different version of the updated div. Its like the old content is not erased before the new content is added.

If I click on the first link and scroll I get the right items OK!.

Then if I click on the second link, when I scroll I get the Item twice (duplicated- it calls the code from the previous ajax call)

Then if I click on the third link, when I scroll I get the Item 3 times. (it calls the code from the 2 previous ajax call )

When I use the Chrome debugger I see that it goes first in the code that have received the parameter EXAMPLE_1 then it goes in the code that has received the parameter EXAMPLE_2 etc

But this code should has been overridden by the call of the EXAMPLE_2 link.

It is difficult to explain I don't know if someone understand what Im trying to explain but I give it a try :) and again sorry for my english.

Thanks

2
  • Please add code where you actually apply changes to the page. There is nothing wrong with your browser, you just missing something in your code and this is not displayed in your question. Commented Nov 26, 2013 at 22:57
  • Try my updated function; it should help. Commented Nov 27, 2013 at 4:54

3 Answers 3

1

I'm a bit picky about POST and GET, so even though Wayne is technically correct, the fact that you are retrieving data makes your use of GET the right way of doing it.

The way around caching is either by using jQuery's ajax method and setting cache to false, like so:

$.ajax({
    url: "/items/next/?list_name=" + CODE,
    type: 'GET',
    success: function(data) {
        $('#content-to-update').html(data);
    },
    cache:false,
    error: function(e) {
        alert("Server failure! Is the server turned off?");
    }
});

You can also trick the browser by adding a random string to the end of the URL, which is what I usually do. Something like this:

$.get("/items/next/?list_name=" + CODE + '&cache_buster=' + (new Date()).getTime().toString(),  function(data){

        //executing some javascript to display next items  

        }).done(function() {
             loading = false;
        })
Sign up to request clarification or add additional context in comments.

2 Comments

I upvoted because your answer is usefull. What is the point of adding ´&cache_buster´ parameters how do you use it in the next function() ?
The cachebuster makes the browser think it's loading a different page so it won't load it from the cache. You don't have to name it cache_buster, you just need a unique query string parameter in the URL. Some people use version numbers, so you could have v=1.2.3 or whatever. Not sure what you mean by "next function" though
1

If you are using .html() to set the content, the error is definitely somewhere else.
Ensure that you are not appending the new content to the div, which seems like what you are doing.
Also, your functions should act independently of one another. Your current process seems to support that, but your problem seem to suggest otherwise.
Try the suggestions first and if they don't work, post more code.

Update

Try this:

 
var loading = false;
function executeSomeAjax(CODE){
    $(window).scroll(function () {
        var winTop = $(window).scrollTop();
        var docHeight = $(document).height();
        var winHeight = $(window).height();

        //if user reach bottom of the page
        if  (!loading && (winTop / (docHeight - winHeight)) > 0.95) {
            loading = true;


            //the CODE parameter is different on each call from the links that I
            //talked earlier. 
            $.get("/items/next/?list_name=" + CODE,  function(data){

            //executing some javascript to display next items  

            }).done(function() {
                 loading = false;
            })
        }
    });
  });
}
 

As you can see, the variable loading is now a global variable. I suspect that it was a local variable in your original function and as a result was set to false anytime the function ran.
Making it a global variable should resolve your issue.


Hope this helps.

6 Comments

I am using .html and there is no way to see the javascript in the DOM tree I can only see it with the Chrome javascript debugger. And it effectively call all the different code simultaniously. If I use $.ajaxSetup({async:false}); I dont have any problem anymore.
the event is wired to a button click; so, unless you are clicking three buttons at the same time OR something else in your code is calling them all at once, all of them shouldn't execute simultaneously.
It is the code in the updated div that is executed simultaneously. When I scroll. Read my question again
What does the variable loading do? You need a way to prevent simultaneous loadings.
The loading variable is to prevent simultaneous Ajax calls and it works.
|
0

UPDATE

Ok this is the final working code thanks to everybody for helping me out !

I think the problem was coming from low memory on my computer. The code you see below was used yesterday and was not working.

Since I rebooted the computer this morning everything works like a charm. I have 4GO of memory and working with Grails 2.2.2 and Intellij IDEA Im often with 100Mo of memory left I guess this should have a side effect. I cant see other explanations. If That can help anyone to read this post

    var loading = false;
    function nextProject(){
        $('.logo').html('<img src="/images/ajax-loader-transparent.gif">');
        $.ajax({
            type:'GET',
            url: "/project/next/",
            data:"list_name=" + CODE,
            beforeSend:function(){
                console.log("loading : " + loading)
            }
        }).done(function(data) {
            if(data != ""){
                var arrayOfObjects = eval(data);
                for(var i=0; i < arrayOfObjects.length; i++){
                    TrackManager.newTrack(btoa(arrayOfObjects[i].base64Params));
                    var projectMgr = new ProjectManager(arrayOfObjects[i].id);
                    projectMgr.socialShare();
                    <sec:ifNotLoggedIn >
                        projectMgr.runDeny();
                    </sec:ifNotLoggedIn>
                    <sec:ifLoggedIn >
                        projectMgr.runGranted(arrayOfObjects[i].likeUp, arrayOfObjects[i].inPlayList );
                    </sec:ifLoggedIn>
                    INC++;
                }
                loading = false;
                $('.logo').html('<img src="/images/soundshare_logo_32.png">');
                console.log(INC + "/" + PROJECT_COUNT );
            }
        }).fail(function(){
            console.error("Ajax error!")
        });
    }

    $(window).scroll(function(){
        var winTop = $(window).scrollTop();
        var docHeight = $(document).height();
        var winHeight = $(window).height();
        if  ((winTop / (docHeight - winHeight)) > 0.95) {
            if(INC < PROJECT_COUNT){
                if(!loading){
                    loading = true;
                    nextProject()
                }
            }
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.