I've my site pages structure as
1) index.php which calls addline.php using ajax and the html returned is appended to the index.php
2) the addline.php calls another page more.php using ajax which again appends the returned html to it
3) Again more.php calls another file update.php and in the update.php, I've my following js codes
var number = parseInt("<?php echo $delFlag; ?>");
if ( number == 1) {
// Calling updateLine() function after 5 mins
timer = setTimeout("updateLine()",1000*5*60);
}
function updateLine() {
var flagId = <?php echo $flagId; ?>;
var dataPass = 'flagId=' + flagId;
$.ajax({
type: "POST",
url: "proc/updateLine.php",
data: dataPass,
cache: false,
success: function(){
// Show error if error is there
}
});
}
All the time, my location is still index.php.
The javascript function works properly if I do not reload the page. If I reload the page, it doesn't work. I want the setTimeOut() call to be active in the background even after the reload takes place. It should trigger the function call after 5 mins.
How do I achieve it??
Reloading a page resets the Javascript state and there is no direct way to keep things running in the background.
If the requirement is to continue the timeout counter automatically after the page reload, then the counter state has to be persisted somehow.
It means that every timeout start has to be accounted for. One option would be to do it with PHP and load and unload events, along the lines of:
// timeout.php -- persists and returns the last timeout start by session
<?php
session_start();
$key = 'lastTimeoutStart';
if (isset($_GET[$key]))
$_SESSION[$key] = $_GET[$key];
else if (isset($_SESSION[$key]))
echo $_SESSION[$key];
?>
Plus the Javascript part that handles persisting and loading:
var lastTimeoutStart = 0;
if ( number == 1) {
// Calling updateLine() function after 5 mins
lastTimeoutStart = new Date().getTime();
timer = setTimeout("updateLine()",1000*5*60);
}
//
// Other code
//
$(document).load(function () {
$.get('timeout.php', function (data, textStatus, jqXHR) {
var persistedStart = data.lastTimeoutStart;
var tempTimeout = persistedStart + 1000*5*60 - new Date().getTime();
if (tempTimeout > 0) {
clearTimeout(timer);
timer = setTimeout("updateLine()", tempTimeout);
}
});
});
$(document).unload(function () {
var data = {"lastTimeoutStart": lastTimeoutStart};
$.get('timeout.php', data, function (data, textStatus, jqXHR) {});
});
There may be bugs in the above code but hopefully you get the idea.
Related
I am using CodeIgniter.
I have a function called as reloadCart(). I have to reload this function every time because this function will reload the amount anything changes happened. This is working perfect but the issue is when I am refreshing the page then it displays the new amount.
$(document).ready(function(){
reloadCart();// function reload on page refresh
function reloadCart(){
$.ajax({
url: "<?php echo base_url(); ?>Member_controller/primaryCartload",
context: document.body,
success: function(data){
if (data !=0) {
var obj = JSON.parse(data);
if (obj.qty != 0) {
$('#totalDetails').html(obj.cart_total);
$('#totalQty').html(obj.totalQty);
}
}
else{
//alert('empty')
$('#totalDetails').html('0');
$('#totalQty').html('0');
}
}
});
}
});
Can we use something like?
load({
reloadCart();
});
You can just update your price by running that AJAX call time to time, for that you'll need to set a time after that specific time your call will be run again.
var count = 20;
setInterval(function () {
count--;
if (count === 0) {
count = 20;
reloadCart();
}
}, 1000);
So after every 20 sec this function will be called, you can amend it as required.
So I have been working on this for hours now, I have read a bunch of StackOverflow posts and I am still having no luck.
I have a page that has 2 sections to it, depending on the int in the database will depend on which section is being displayed at which time.
My goal is to have the page look to see if the database status has changed from the current one and if it has then refresh the page, if not then do nothing but re-run every 10 seconds.
I run PHP at the top of my page that gets the int from the database
$online_status = Online_status::find_by_id(1);
I then use HTML to load the status into something that jquery can access
<input type="hidden" id="statusID" value="<?php echo $online_status->status; ?>">
<span id="result"></span>
So at the bottom of my page, I added some jquery and ajax
$(document).ready(function(){
$(function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$newResult = $('#result').html(data);
window.setInterval(function(){
liveCheck();
}, 10000);
}
}
});
});
liveCheck();
});
this then goes to another PHP page that runs the following code
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
echo "<script>location.reload();</script>";
}else{
}
}
the jquery then loads into the HTML section with the id of "result" as shown earlier. I know this is a very bad way to do this, and as a result, it will work at the beginning but the longer you leave it on the page the slower the page gets, till it just freezes.
If anyone is able to point me towards a proper method I would be very grateful.
Thank you!!
js:
(function(){
function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(data.trim() == ''){
location.reload();
}else{
$('#result').html(data);
window.setTimeout(function(){
liveCheck();
}, 10000);
}
}
});
}
$(function(){
liveCheck();
});
})(jQuery)
php:
<?php
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
$data = '';
}else{
$data = 'some html';
}
echo $data;
}
Your page is slowing down because you are creating a new interval every time you call the liveCheck function. Over time, you have many intervals running and sending requests to your PHP file concurrently. You can verify this behavior by opening the developer console in your browser and monitoring the Network tab.
What you should do instead is set the interval once, and perform the $.ajax call inside that interval. Additionally, it's good practice to not send a new request if a current request is pending, by implementing a boolean state variable that is true while an request is pending and false when that request completes.
It looks like the intended behavior of your function is to just reload the page when the $online_status->status changes, is that correct? If so, change your PHP to just echo true or 1 (anything really) and rewrite your JS as:
function liveCheck() {
if (liveCheckPending == true)
return;
liveCheckPending = true;
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST'
}).done(function(data){
if (!data.error)
location.reload();
}).always(function(data){
liveCheckPending = false;
});
}
var liveCheckPending = false;
setInterval(liveCheck, 10000);
I have a .txt file on my server. I need a script to read it in an infinite loop, at every 500ms. Basically, that variable should be updated every 500ms and displayed on a .php page.
Any suggestions?
here is the code for reading the text file;
readTextFile("file:///C:/your/path/to/file.txt");
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
I use setTimeout because request maybe waits a long time.If you want no waiting use setInterval instead of setTimeout but give heed to ram usage.
var currentText=null;
var getText=function(){
$.ajax({
url: "http://www.sample-videos.com/text/Sample-text-file-10kb.txt",
success: function (r) { currentText=r;alert(currentText);setTimeout(getText,500); },
error: function () { alert('it doesnt work') }
});}
setTimeout(getText,500)
I have two javascript/jquery functions in my app, there is always refresh() function, which grabs data from database and redraw frontend view.
One of methods is sending data into PHP function, which makes simple insert to MySQL database, second edits it, here they are (they're the same, so I post only one):
function insertedit()
{
$('.res').each(function()
{
$.post("/controller/method/",{id: id},function(data,status,xhr)
{
if(status=="success")
{
}
})
});
refresh();
}
When I'm trying to insert data with this function, all works fine and my view is redrawing asynchronously, but when i'm trying to edit data with it - I have to refresh page to see updated view. I think, that edit operation takes more time than insert and my refresh function, which grabs data from SQL just grabs the old data (undeleted record) - how can I fix it?
EDIT
$(function()
{
refresh();
});
function insertedit(){
var $promises = [];
$('.res').each(function()
{
$promises.push(
$.post("/controller/metgod/",{id, id},function(data,status,xhr)
{
if(status=="success")
{
}
})
);
});
$.when.apply($, $promises).then(function() {
refresh();
});
}
Use promises
function insertedit()
{
var $promises = [];
$('.res').each(function(id){
var $this = $(this);
$promises.push(
$.post("/controller/method/", {'id': $this.attr('id')}, function(data,status,xhr){
$this.text(data); // success
})
);
});
$.when.apply($, $promises).then(function(){
refresh();
});
}
See the fiddle here, it works http://jsfiddle.net/69eMp/4/
I have had use for such a solution at some point, and here was my solution (here's a live demo here) :
/**
* Class that will handle delayed function calls
* #param fn the funciton to call
* #param ctx the context to use as 'this' inside the function
* #param delay delay in millis
*/
var AsyncCall= function(fn, ctx, delay) {
var timer = null;
ctx = ctx || window;
delay = delay || 1;
return function() {
// prevent calling the delayed function multiple times
if (timer) clearTimeout(timer);
var args = arguments;
timer = setTimeout(function() {
timer = null;
fn.apply(ctx, args);
}, delay);
};
};
// wrap the 'refresh' funciton inside the async call object with a 200 millis delay
var refreshAsync = new AsyncCall(refresh, null, 200);
function insertedit()
{
$('.res').each(function()
{
$.post("/controller/method/",{id: id},function(data,status,xhr)
{
if(status=="success")
{
}
// schedule calling 'refresh'
refreshAsync();
})
});
}
The reason why this would be preferred is that you don't have to refresh every Ajax requests. With this, it will only execute the refresh function fewer times than if you refresh every single time. And 200 milliseconds is not so long, but enough for Ajax calls to return and is not noticeable by the users.
I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...