//
you're reading...

JavaScript

jQuery keepalive

Für manche Projekte brauchte ich schon die Möglichkeit, die PHP-Session am Leben zu halten ohne dass der Besucher aktiv auf der Webseite etwas macht. Das kann man ganz einfach erreichen indem man in gewissen Abständen, z.B. 5 Minuten einen Ajax-Call auf eine PHP Datei macht in der die Session berührt wird.

Die jQuery Funktion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$.keepAlive = {
    options: {
        url: "myScript.php",
        delay: 60*5 //5 minuten (Angabe in Sekunden!)
    },    
    dummyfn: function(){ },
    
    timeoutobj: {
        id: -1
    },
    
    set: function(options, ondummyfn) {
        if (this.timeoutobj.id > -1)
            clearTimeout(this.timeoutobj);
    
        if (options)
            $.extend(this.options, options);
    
        if (ondummyfn)
            this.dummyfn = ondummyfn;
    
        this.timeoutobj.id = setTimeout(function() {
            $.keepAlive.beat();
        }, this.options.delay*1000);
    },
    
    beat: function() {
        $.post(this.options.url, { });
        this.timeoutobj.id = setTimeout(function(){
            $.keepAlive.beat();
        }, this.options.delay*1000);
        this.dummyfn();
    }
};

Anwendung:

1
2
3
$.keepAlive.set({
    url: "/keepAlive.php"
});

wobei url und delay optional sind, $.keepAlive.set(); reicht aus um den Intervall mit den Standard-Parametern zu starten.

Discussion

No comments yet.

Post a Comment