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)
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.
Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
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 ...
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.
I am running a shell script in the background and redirecting the output to a log file in php. I want to display the contents from the log file on the page. I am able to do that using the code below.
<?php
$logfile = "hello";
?>
function displayOutput()
{
var html = <?php
echo filesize($logfile)
? json_encode(file_get_contents($logfile))
: '"Log file is getting generated"';
?>;
document.form.text1.value = html;
}
However, the log file keeps updating till the script completes executing. How can i reload the updated contents from the file on the same page?
The technique that I developed + discuss here may be useful:
https://web.archive.org/web/20150206001444/http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/
It's been around for a while + works well.
You need to set an interval timer to call your function every n seconds. Have a look at this answer to help you out - how to schedule ajax calls every N seconds?.
setInterval(displayOutput, (10 * 1000));
// reload log contents every 10 seconds
Maybe what you want basic XMLHttpRequest usage.
I am not really php guy, neiter javascript guru, just trying to give you an idea
function refreshText()
{
if (window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else // for IE 5/6, just in case
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","/page.php?action=download_log_file", false);
xhttp.send();
document.form.text1.value = xhttp.responseXML;
}
setInterval(refreshText, (10 * 1000)); // refresh text1.value every 10 seconds
same thing using jQuery
setInterval(function {
$.get('/page.php?action=download_log_file', function(data) {
$('#text1').val(data);
});
}, (10 * 1000));
The handler script at the server just prints file data, see
http://www.w3schools.com/xml/xml_server.asp for example
I've implemented "COMET-like" functionality recently to do just this. The way it works is to have an AJAX poll with a long timeout:
var lines = 0
function getLog(file, lines) {
$.ajax({
type: 'POST',
url: 'http://thissite.com/getLogFile.php?File=' + file + '&Lines=' + lines,
dataType: 'json',
timeout: 400000,
error:
function() {
return false;
},
success:
function(data) {
if (data.Error) {
alert(data.Message)
} else {
if (data.Lines > lines) {
// do something with data.LogLines, e.g. add to a textarea
}
getLogFile(file, data.Lines)
}
}
})
}
The back end script then simply loops like this:
Count the number of lines in the log file
If it's the same as lines, sleep (say for a second), then go back to 1
If the number of lines is greater, return the new lines, and the new line count, and exit
After some number of iterations (I use 100), exit and return the existing line count
The data structure returned by the back end script is JSON:
{
Error: // 0 or 1,
Lines: // Number of lines
Text: // New lines from log file
}
This works just like 'tail -f' in UNIX, but in a browser!