reading a txt file with AJAX

inkexit50

New Member
Messages
2
Reaction score
0
Points
0
I have a text file (test.txt) that is being uploaded to my x10 premium site via another program on my home pc. The file is technically in CSV format, but as of right now all it has in it is one integer. I've been working on the code posted below for the html, the javascript, and the php, but am running into a few walls.


To understand the whole concept, this is what I'm trying to do: I'm trying to have the javascript check the txt file via php file every 10 seconds, and only refresh the data on the html page if the integer saved in text.txt has changed.


I'm not sure how to pass a variable from php to the javascript. I could use echo and just have the php 'print' out the integer, but eventually test.txt will have a lot more info in it and I'm gonna have to pass a bunch of variables inbetween the javascript and the php anyway.


Also, this is especially ignorant of me, but I'm not sure how to call a javascript function every 10 seconds.


Php
PHP:
<?php


$handle = fopen("http://www.MySite.com/Signal/test.txt", "r"); 


while (($data = fgetcsv($handle, 1, ",")) !== FALSE) 
{ 
$PHPSignal=$data[1]; 
echo $PHPSignal;
echo "</br>"; 
} 

?>



javascript:


Code:
// JavaScript Document




var response;
var request = false; // The object to handle the request for data
var reqType = "GET"; // Make the request type a GET as opposed to a POST
var url = "http://www.MySite.com/ReadCSV.php";
var asynch = true; // Make this an asynchronous request
var interval = 1000 * 1;    // Update the page at X second intervals






function getData()
{
    //
    // Do the first request, then
    // 
    httpRequest();
    
    //
    // send the request at intervals
    //
    setInterval(httpRequest, interval);
}






/* Wrapper function for constructing a Request object.*/
function httpRequest()
{
    //
    // Only create the request object.
    //
    //Mozilla-based browsers
    if(window.XMLHttpRequest)
{
        request = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject)
    {
        // IE browsers
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request)
        {
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request)
    {
       initReq(reqType,url,asynch); // Initialize the request
    }  
    else 
    {
        alert("Your browser does not permit the use of all "+
        "of this application's features!");
    }
}






/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool)
{
    /* Specify the function that will handle the HTTP response */
    request.onreadystatechange = handleResponse;
    
    //
    // In order to prevent IE browsers from returning a cached version of
    // the XML file we to append a unique value to the end of the URL. This is
    // ignored by the responder script; but ensures the page gets updated.
    //
    var urlToSend = url + "?key=ms" + new Date().getTime();
    request.open(reqType, urlToSend, bool);
  
    request.send();
}


//event handler for XMLHttpRequest
function displayDocInfo(doc)
{
if (request.readyState == 4)
{
if (request.status == 200) 
{
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(/\n/g, "");
} else
{ 
alert("status is " + request.status);
}
}
}





html:


HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ThumbScalp.com - The best realtime signals of the market.</title>




<SCRIPT language="JavaScript" SRC="/ThumbJavascript.js"></SCRIPT> 




</head>




<body>
<div>




<A HREF="javascript:getData()">Click to update.</A> 


</div>
</body>
</html>
 

Bryon

I Fix Things
Messages
8,149
Reaction score
101
Points
48
Can you provide the URL containing Signal/test.txt? Any that I try based off of your domain result in a 404 error.
 

inkexit50

New Member
Messages
2
Reaction score
0
Points
0
It's outside the www directory. I put it there because I want this txt file to be secure, that the only thing that can access it is the php script. I can move it to the www directory though in the meantime.

I'll just make another copy and put it in www

now there should be one here

www.thumbscalp.com/test.txt
 
R

ryanmaelhorn77

Guest
I really need to get this going. Shouldn't be more than an hour of work for a good ajax pro. I'm willing to PAY to have someone do this for me. If you have a paypal account and want some quick money, please email CreateModify@gmail.com.
 

scopey

New Member
Messages
62
Reaction score
0
Points
0
What is the error you are getting?

If you are not sure, try using the firebug addon for firefox to check your javascript. Right now, I can't seem to find where your function 'handleResponse' is defined. You have set that function to be called when the readystate of your ajax request changes.

Your AJAX is a little hard to understand. I think you call a few too many functions which is a little confusing.

Here is my suggestion:

Under the initReq() function, change the following line

Code:
request.onreadystatechange = handleResponse;

to

Code:
request.onreadystatechange=function()
    {
        if(request.readyState==4)
        {
            displayDocInfo(request.responseText);
        }
    }

Then edit the 'displayDocInfo(response)' function to

Code:
response = response.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(/\n/g, "");
 

farscapeone

Community Advocate
Community Support
Messages
1,165
Reaction score
27
Points
48
Why don't you use jQuery and it's AJAX functions? It's easy and it'll save you a lot of time and trouble.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
I'm not sure how to pass a variable from php to the javascript. I could use echo and just have the php 'print' out the integer, but eventually test.txt will have a lot more info in it and I'm gonna have to pass a bunch of variables inbetween the javascript and the php anyway.

Use JSON as a data-interchange format. In the PHP script, store the variables in an object or array and output the result of json_encode. For example:
PHP:
$foo='bar';
$funcs = array('cos', 'sec', 'tan', 'sin')
echo json_encode(compact('foo', 'bam'));

To reduce network traffic, make use of the If-Modified-Since and ETag/If-None-Match headers (use both since support will vary among browsers). For example:
PHP:
$finfo = stat($file);
$etag = "$finfo[mtime]-$finfo[size]";
if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $finfo['mtime'] <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) 
 || (isset($_SERVER['HTTP_IF_NONE_MATCH']) 
          && ($_SERVER['HTTP_IF_NONE_MATCH'] = '*' || $_SERVER['HTTP_IF_NONE_MATCH'] == $etag)))
{
    header('HTTP/1.0 304 Not Modified');
} else {
    header('Last-Modified: ' . date('r'));
    header("ETag: $etag");
    // process & print file
    ...
}

Client side, use a JSON parser (such as JSON.org's open source parser). Newer browsers have native JSON parsers (FF 3.5, IE 8, Opera 10.5, Safari 4.0.3(?), Chrome 2(?)), though a fair number of people are using older browsers so you can't yet rely on them. JS libraries (such as jQuery) often have JSON parsers (for jQuery, pass a data type of 'json' to any of the AJAX methods or use getJSON/). For example:
Code:
function update(url, successHandler) {
    $.ajax({
        url: url, 
        success: function (data, status) {
            if (status != 'notmodified') {
                successHandler(data, status);
            }
        }, 
        type: 'json',
        ifModified: true
    });
}

function displayDocInfo(data, status) {
    $('#order').val(data.order);
    $('#address').html(data.address);
}

var updateIval = setInterval(updateSignal, 10000, '/ReadCSV.php', displayDocInfo);
jQuery 1.2 and newer support ETag/If-None-Match and Last-Modified/If-Modified-Since headers when you set the ifModified parameter.

Also, this is especially ignorant of me, but I'm not sure how to call a javascript function every 10 seconds.
You've got it in the JS: setInterval. The second argument is the interval period in milliseconds.

Code:
var funcIval = setInterval(func, 10000);

You stop an interval using clearInterval.



Don't use global variables, which ThumbJavascript.js does.

What does the data stored in the CSV represent? URIs are names. "/ReadCSV.php" is a verb phrase and file extension, both of which should be done away with (though the extension is largely a cosmetic matter). Something like "/signal" would be better, and "/trade_signal" or "/TradeSignal" is better still. See also "Cool URIs Don't Change" and the various posts on extensionless URLs.
 
Last edited:
Top