alain mardo alain mardo - 6 months ago 14
JSON Question

how to update variable dynamically of currency rate WITH php/json/ajax

I would like to know how to update variable dynamically of currency rate WITH

php/AJAX/json
that
$CurrencyValue
(the currency value from yahoo finance) will update only if the variable is different than it was before.

For example:

on 01/01/2016 10:00 USDINR gate was 67.454.
1/01/2016 10:01 USDINR gate was 67.104 (the variable $CurrencyValue be updated).
1/01/2016 10:02 gate of USDINR remains 67.104 (the variable $CurrencyValue not be updated).
1/01/2016 10:03 USDINR gate was 67.024 (so the variable $CurrencyValue be updated).


It is important the page will not refreshed, only the variable
$CurrencyValue
also if the variable changed I would like to get The exact date.

<?php
$from = 'USD'; $to = 'INR'; $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; $currencyValue = 0; $handle = fopen($url, 'r'); if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$currencyValue = $data[1];
}
fclose($handle);

} $date = date('l jS \of F Y h:i:s A');

?>


Value of 1 USDINR is <?php echo $currencyValue. ' - ' .$date; ?>


Thank you

Answer
<?php
if(isset($_GET['fetchOnly'])){
    $from   = 'USD';
    $to     = 'INR';
    $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; 
    $response = array();
    $handle = fopen($url, 'r'); 
    if ($handle) { 
        while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE) 
        { 
            $response['rate'] = $data[1]; 
            $response['date'] = $data[2];
            $response['time'] = $data[3];
        }
        fclose($handle);
        fclose($handle);
    }  
    echo json_encode($response);
    die();
} 
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();

function fetchRate() {
    // create the new AJAX Object
    xmlhttp = new XMLHttpRequest();
    // this handles the request
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
            // if the request came back successfully
            if(xmlhttp.status == 200){
                // write the response to a div
                div = document.getElementById("responseText")
                div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
            }else{
            // if the request had an error
                div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
            }
            // rerun this function to fetch updates
            setTimeout(fetchRate,3000);
        }
    };
    // open the AJAX Object
    xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
    // send the AJAX request
    xmlhttp.send();
}

Comments