I'm trying to figure out how to update my live data, I found some examples on Google of Ajax but I can't seem to get them to work.
The part that contains and places the live data in a paragraph is :
$file = "Data.txt";
$data = file($file);
$line = $data[count($data)-1];
for($i=1;$i<6;$i++){
switch ($line) {
case $i:
echo "<p class ='bus".$i."'> <img id='bus' src = 'bus.png'> </p>";
break;
}
}
This is the full html file
<!DOCTYPE>
<html>
<head>
<title>Bus</title>
<link rel="stylesheet" href="stijlenbestand.css">
</head>
<body>
<?php
//aanmaken 5 bushaltes
echo '<figure>';
for($i=1;$i<6;$i++){
echo "<img src = 'bushalte.png'>";
}
echo '</figure>';
//laatste lijn van tekstbestand.
$file = "Data.txt";
$data = file($file);
$line = $data[count($data)-1];
for($i=1;$i<6;$i++){
switch ($line) {
case $i:
echo "<p class ='bus".$i."'> <img id='bus' src = 'bus.png'> </p>";
break;
}
}
?>
</body>
</html>
For a live update you need two parts.
First is the part where your page is and the second part is where your data comes from.
Php is a very static language. Once your script is finished it won't do anything anymore.
For a "live-website" you need Javascript.
if you want to use jQuery i would recommend you to use the jQuery.post() function.
jQuery Code in your Website:
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Your test.php
if(isset($_POST['name'])) {
//Do Some Stuff
$a = 'var a';
echo json_encode($a);
}
This is not ajax. Ajax means having frontend code fetching new information on the background. This information then gets appended to the DOM. (Usually the information is transfered as JSON encoded data but lets keep that out of scope.)
For this you need two files:
A frontend file (for instance static index.html with some content)
A backend file providing the data
The frontend file would run some JavaScript then requests the backend file
The backend file responds and returns some output
The javascript adds output to the DOM.
There are many ways of doing this and I don't have the te time to explain all of it here but you might want to have a look at: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
This provides a simple example based on jQuery.
Related
This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>
Probably i didnt explain very well, i updated the code to turn more easy to see what i want.
I need to load a external html file in that "div external_page....", i thing that the best way is to load a file in the php file(External PHP content), tell me if im wrong :)
This is the demo: http://vasplus.info/demos/load_and_refresh_div_every_10_seconds/index.php
(UPDATE)
<script language="javascript" src="js/jquery_1.5.2.js"></script>
<div id="external_page_content_displayer">External page contents will be here</div>
<!-- EXTERNAL PHP CONTENTS-->
<?php
srand((float) microtime() * 10005224);
$lines = file('ajax/rssatom/rss-atom.html');
$This_Page_Content = array($lines,
"teste","teste","teste");
$This_Page_Content_Rand_Keys = array_rand($This_Page_Content, 2);
$This_Page_Content_Displayer = $This_Page_Content[$This_Page_Content_Rand_Keys[0]] . "\n";
echo strip_tags($This_Page_Content_Displayer);
?>
<!-- LOAD FUNCTION-->
<script>
function Load_external_content()
{
$('#external_page_content_displayer').load('external_content.php').hide().fadeIn(3000);
}
setInterval('Load_external_content()', 10000);
</script>
Regards
You can try with this:
$lines = file('ajax/rssatom/rss-atom.html');
There is a Dutch news website at: nu.nl
I am very interested in getting the first url headline which is resided over her:
<h3 class="hdtitle">
<a style="" onclick="NU.AT.internalLink(this, event);" xtclib="position1_article_1" href="/buitenland/2880252/griekse-hotels-ontruimd-bosbranden.html">
Griekse hotels ontruimd om bosbranden <img src="/images/i18n/nl/slideshow/bt_fotograaf.png" class="vidlinkicon" alt=""> </a>
</h3>
So my question is how do I get this url? Can I do this with Jquery? I would think not because it is not on my server. So maybe I would have to use PHP? Where do I start...?
Tested and working
Because http://www.nu.nl is not your site, you can do a cross-domain GET using the PHP proxy method, otherwise you will get this kind of error:
XMLHttpRequest cannot load http://www.nu.nl/. Origin
http://yourdomain.com is not allowed by Access-Control-Allow-Origin.
First of all use this file in your server at PHP side:
proxy.php (Updated)
<?php
if(isset($_GET['site'])){
$f = fopen($_GET['site'], 'r');
$html = '';
while (!feof($f)) {
$html .= fread($f, 24000);
}
fclose($f);
echo $html;
}
?>
Now, at javascript side using jQuery you can do the following:
(Just to know I am using prop(); cause I use jQuery 1.7.2 version. So, if you are using a version before 1.6.x, try attr(); instead)
$(function(){
var site = 'http://www.nu.nl';
$.get('proxy.php', { site:site }, function(data){
var href = $(data).find('.hdtitle').first().children(':first-child').prop('href');
var url = href.split('/');
href = href.replace(url[2], 'nu.nl');
// Put the 'href' inside your div as a link
$('#myDiv').html('' + href + '');
}, 'html');
});
As you can see, the request is in your domain but is a kind of tricky thing so you won't get the Access-Control-Allow-Origin error again!
Update
If you want to get all headlines href as you wrote in comments, you can do the following:
Just change jQuery code like this...
$(function(){
var site = 'http://www.nu.nl';
$.get('proxy.php', { site:site }, function(data){
// get all html headlines
headlines = $(data).find('.hdtitle');
// get 'href' attribute of each headline and put it inside div
headlines.map(function(elem, index){
href = $(this).children(':first-child').prop('href');
url = href.split('/');
href = href.replace(url[2], 'nu.nl');
$('#myDiv').append('' + href + '<br/>');
});
}, 'html');
});
and use updated proxy.php file (for both cases, 1 or all headlines).
Hope this helps :-)
You can use simplehtmldom library to get that link
Something like that
$html = file_get_html('website_link');
echo $html->getElementById("hdtitle")->childNodes(1)->getAttribute('href');
read more here
I would have suggested RSS, but unfortunately the headline you're looking for doesn't seem to appear there.
<?
$f = fopen('http://www.nu.nl', 'r');
$html = '';
while(strpos($html, 'position1_article_1') === FALSE)
$html .= fread($f, 24000);
fclose($f);
$pos = strpos($html, 'position1_article_1');
$urlleft = substr($html, $pos + 27);
$url = substr($urlleft, 0, strpos($urlleft, '"'));
echo 'http://www.nu.nl' . $url;
?>
Outputs: http://www.nu.nl/buitenland/2880252/griekse-hotels-ontruimd-bosbranden.html
Use cURL to retrieve the page. Then, use the following function to parse the string you've provided;
preg_match("/<a.*?href\=\"(.*?)\".*?>/is",$text,$matches);
The result URL will be in the $matches array.
If you want to set up a jQuery bot to scrape the page through a browser (Google Chrome extensions allow for this functionality):
// print out the found anchor link's href attribute
console.log($('.hdtitle').find('a').attr('href'));
If you want to use PHP, you'll need to scrape the page for this href link. Use libraries such as SimpleTest to accomplish this. The best way to periodically scrape is to link your PHP script to a cronjob as well.
SimpleTest: http://www.lastcraft.com/browser_documentation.php
cronjob: http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
Good luck!
Ok, what I am trying to do is make a javascript loop of images, but first I have to get a list of the images. In javascript there is no way to directly grab this text file... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt but it can be done eaisly in php, I am currently gettung the txt file using php, but the javascript cannot read the variable. How can I make javascript be able to read this variable. Here is what I have...
<?php
$file = "http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"; //Path to your *.txt file
$contents = file($file);
$string = implode($contents);
echo $string;
?>
<script type="text/javascript">
function prnt() {
var whatever = "<?= $string ?>";
alert(whatever);
}
</script>
You can use echo or print to write to the page in PHP.
var whatever = "<?php echo $string; ?>";
Although, if the file has line breaks in it, you will need to remove those.
Make it a bit more interesting: go ahead and split the fields and use JSON encoding. It should read directly in javascript without needing to call JSON.parse() on the client.
<?php
$lines = file_get_contents('http://...');
$lines = explode("\n",trim($lines));
foreach ($lines as &$line) {
$line = preg_split('/,? /',$line);
}
$js = json_encode($lines);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var dar = <?php echo $js; ?>;
</script>
</body>
</html>
You should also consider using a local proxy to cache the results of that file if you plan to run this frequently and especially if you are going to serve it up on a public web server somewhere. Store the file locally as "noaa_data.txt" and have a second script on a cron job (12 hours or something):
<?php
file_put_contents("/var/www/noaa_data.txt",file_get_contents("http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"));
?>
I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.