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:
$.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:
$.keepAlive.set({ url: "/keepAlive.php" });
wobei url und delay optional sind, $.keepAlive.set(); reicht aus um den Intervall mit den Standard-Parametern zu starten.