How to get number of video views with YouTube API? - javascript

The question is very simple. How to get number of video views with YouTube API?
The task is simple but I would like to use that query on large number of videos very often. Is there any way to call their Youtube API and get it? (something like facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com)

I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:
<?php
$video_ID = 'your-video-ID';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>
Ref: Youtube API - Retrieving information about a single video

You can use the new YouTube Data API v3
if you retrieve the video, the statistics part contains the viewCount:
from the doc:
https://developers.google.com/youtube/v3/docs/videos#resource
statistics.viewCount / The number of times the video has been viewed.
You can retrieve this info in the client side, or in the server side using some of the client libraries:
https://developers.google.com/youtube/v3/libraries
And you can test the API call from the doc:
https://developers.google.com/youtube/v3/docs/videos/list
Sample:
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}
Authorization: Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent: Google APIs Explorer
Response:
200 OK
- Show headers -
{
"kind": "youtube#videoListResponse",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"id": "Q5mHPo2yDG8",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
"statistics": {
"viewCount": "36575966",
"likeCount": "127569",
"dislikeCount": "5715",
"favoriteCount": "0",
"commentCount": "20317"
}
}
]
}

Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.
Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.
You will need to create an API key via Google Developer Console first.
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
alert("viewCount: " + data.items[0].statistics.viewCount);
});
</script>

Here is a small code snippet to get Youtube video views from URL using Javascript
Demo of below code
function videoViews() {
var rex = /[a-zA-Z0-9\-\_]{11}/,
videoUrl = $('input').val() === '' ? alert('Enter a valid Url'):$('input').val(),
videoId = videoUrl.match(rex),
jsonUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json',
embedUrl = '//www.youtube.com/embed/' + videoId,
embedCode = '<iframe width="350" height="197" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>'
//Get Views from JSON
$.getJSON(jsonUrl, function (videoData) {
var videoJson = JSON.stringify(videoData),
vidJson = JSON.parse(videoJson),
views = vidJson.entry.yt$statistics.viewCount;
$('.views').text(views);
});
//Embed Video
$('.videoembed').html(embedCode);}

Why using any api key to retrieve a portion of public html!
Simplest unix command line demonstrative example, using curl, grep and cut.
curl https://www.youtube.com/watch?v=r-y7jzGxKNo | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1
Yes, it get the full html page, this loss has no meaning against the countless advantages.

You can use this too:
<?php
$youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
echo $youtube_view_count;
?>

Using youtube-dl and jq:
views() {
id=$1
youtube-dl -j https://www.youtube.com/watch?v=$id |
jq -r '.["view_count"]'
}
views fOX1EyHkQwc

Use the Google PHP API Client: https://github.com/google/google-api-php-client
Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html
class YouTubeVideo
{
// video id
public $id;
// generate at https://console.developers.google.com/apis
private $apiKey = 'REPLACE_ME';
// google youtube service
private $youtube;
public function __construct($id)
{
$client = new Google_Client();
$client->setDeveloperKey($this->apiKey);
$this->youtube = new Google_Service_YouTube($client);
$this->id = $id;
}
/*
* #return Google_Service_YouTube_VideoStatistics
* Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )
*/
public function getStatistics()
{
try{
// Call the API's videos.list method to retrieve the video resource.
$response = $this->youtube->videos->listVideos("statistics",
array('id' => $this->id));
$googleService = current($response->items);
if($googleService instanceof Google_Service_YouTube_Video) {
return $googleService->getStatistics();
}
} catch (Google_Service_Exception $e) {
return sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
return sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
}

YouTube Data API v3 URL Sample
Source Link
https://www.googleapis.com/youtube/v3/videos?key=[YOUR_API_KEY_HERE]&fields=items(snippet(title,tags,channelTitle,publishedAt),statistics(viewCount))&part=snippet,statistics&id=[VIDEOID]

look at yt:statistics tag.
It provides viewCount, videoWatchCount, favoriteCount etc.

Here an example that I used in my TubeCount app.
I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.
var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[#yt:name='default'](#url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(#countHint)))";
var channel = "wiibart";
$.ajax({
url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
success: function(data){
var len = data.feed.entry.length;
for(var k =0; k<len; k++){
var yt = data.feed.entry[k];
v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
}
}
});

Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API
//Define a constant so that the API KEY can be used globally across the application
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');
function youtube_video_statistics($video_id) {
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return $views;
}
//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');
I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.

PHP JSON
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);
First go through this one by uncommenting
//var_dump(json);
and get views count as:
$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};

You can use JQuery, don't forget to replace Your-Api-Key string from the code below, follow the link to find your own Api key google developers console
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
});
</script>

This probably is not what you want but you could scrap the page for the information using the following:
document.getElementsByClassName('watch-view-count')[0].innerHTML

Related

Get total (video durations) Laravel

I am building a Laravel app in which I upload videos.
To recover the duration of each video, I use the following package which is very good: https://github.com/JamesHeinrich/getID3/
Where I need help is to get the total duration of all the videos and I have no idea how to handle this.
Here is an image that illustrates my research:
And this is how I call GetID3 in my code:
<?php
namespace App\Http\Managers;
use Illuminate\Support\Facades\Auth;
class VideoManager
{
public function getVideoDuration($Videofile)
{
$getID3 = new \getID3();
$pathVideo = 'storage/chapitres-videos/' . Auth::user()->id . '/' . $Videofile;
$fileAnalyze = $getID3->analyze($pathVideo);
$playtime = $fileAnalyze['playtime_string'];
return $playtime;
}
}
$Videofile = $this->videoManager->videoStorage($request->file('video'));
$lecture->video = $Videofile;

Print linked to the logical value

Good morning I wanted help for a code that can use a logical value example:
`` `
function provaIf2(){
var A2=SpreadsheetApp.getActive().getRange('A2').getValue();
var C4=SpreadsheetApp.getActive().getRange('C4').getValue();
if(A2=="") SpreadsheetApp.getActive().getRange('B2').activate();
else if(A2<C4) Print the sheet
else if(A2==C4) Print the sheet
else SpreadsheetApp.getActive().getRange('B3').activate();
}
If you want to print a document using Apps Script, you will have to use Google Cloud Print.
As explained in this article here, you will have to create an Apps Script project in which you include the OAuth2 library. Then you need to get the Google Cloud Print service, send the request and last but not least, print the document.
The below code snippet is used to print the document with the desired options:
function printGoogleDocument(docID, printerID, docName) {
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "NO_DUPLEX"
}
}
};
var payload = {
"printerid" : printerID,
"title" : docName,
"content" : DriveApp.getFileById(docID).getBlob(),
"contentType": "application/pdf",
"ticket" : JSON.stringify(ticket)
};
Reference: Automatically Print Files Placed in Drive with Google Cloud Print and Apps Script.

Loading RSS feed with AJAX: alternatives to Google Feed API?

I've been using the Google Feed API to load RSS feeds, but it looks like Google has shut down the API. For instance, when I try to load the New York Times RSS feed at http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&q=http%3A%2F%2Frss.nytimes.com%2Fservices%2Fxml%2Frss%2Fnyt%2FHomePage.xml, I get this response:
{"responseData": null, "responseDetails": "This API is no longer available.", "responseStatus": 403}
Are there any viable alternatives?
Use Yahoo's YQL API:
select * from xml where url = 'https://news.ycombinator.com/rss'
You can request a JSONP feed by adding a callback parameter to the url
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20'https%3A%2F%2Fnews.ycombinator.com%2Frss'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=mycallback
Deprecated
My plugin, $.jQRSS uses Google Feed and seems to work just fine, given your exact RSS link:
var rss = 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml';
$.jQRSS(rss, { count: 8 }, function (feed, entries) {
console.log([feed, entries]);
$.each(entries, function(i) {
if (this['content']) {
var fieldset = $('<fieldset/>', { title: this.contentSnippet }).appendTo('body'),
legend = $('<legend/>').appendTo(fieldset),
$link = $('<a />', { href: this.link, html: this.title, target: '_blank' }).appendTo(legend),
$date = $('<h5 />', { html: this.publishedDate }).appendTo(fieldset),
$content = $('<div />', { html: this.content }).appendTo(fieldset);
$content.find('br').remove();
}
});
});
fieldset > h5 { float: right; margin-top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://rawgit.com/JDMcKinstry/jQRSS/master/jQRSS.js"></script>
You can use the script feedburner:
<script src="http://feeds.feedburner.com/feeduri?format=sigpro&nItems=10" type="text/javascript"></script>
All information:
https://support.google.com/feedburner/answer/78991?hl=en
One addition to Tony's solution for using YQL - I needed to change the callback value to JSON_CALLBACK to parse the response properly:
'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20\'' + encodeURIComponent(url) + '\'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=JSON_CALLBACK'
You can use PHP to grab a copy of whatever RSS feed you wish to display, then use client side JavaScript to display the results. The main advantage is you're not subject to daily requests limits that way, which most free RSS API services have, or reliability issues.
http://www.javascriptkit.com/dhtmltutors/ajaxticker/index.shtml

Form Information to Appear On Another Page

I am trying to create a form that, once submitted, will be sent to my index.html page for other users to view. I want it so multiple users anywhere in the world can submit information and so the website displays all their information at once.
Here is my submit page's PHP code:
<form action="submit_a_message.php" method="post">
<textarea name="message" cols="60" rows="10" maxlength="500"></textarea><br>
<input type="submit">
</form>
I am trying to figure out how to make the information submited via that form appear on my index.html page. This is the code I found online, but it doesn't work. Why?
<?php>
string file_get_contents ( string $submit_a_message.php [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
<?>
Any help would be greatly appreciated.
To make submitted text avaliable on your index page, you need a place where you would store it. You can use MySQL base to do that, or (if you can't or you really don't want) you can use text file with your texts/posts (that is not really good way, i warned you).
To do that with MySQL you can use a code like this on your submit_a_message.php:
<?php
//connection to database and stuff
...
if $_POST['message'] {
$message = $_POST['message'];
$sql = "insert into `mytable` values $message"; //that is SQL request that inserts message into database
mysql_query($sql) or die(mysql_error()); // run that SQL or show an error
}
?>
In order to show desired vaues from table use above-like idea, your SQL request would be like select * from mytable where id = 123
if your not married to the idea of using php and learning how to manage and access a database you could use jquery and a trird party backend like parse.com
If your new to storing and retrieving data, I would definately reccomend the services that https://parse.com/ offeres. It makes storing and retrieving data trivial. Best of all, the service is free unless your app makes more than 30 API requests per second. I have an app that 61 users use daily and we have never come close to the 30 req per second limit.
To save your info, you could write:
$('document').ready(function(){
$('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button
var Message = Parse.Object.extend("Message"); //create a reference to your class
var newObject = new EventInfo(); //create a new instance of your class
newObject.set("messageText", $("#myMessage").val()); //set some properties on the object, your input will need the id "myMessage"
newObject.save(null, { //save the new object
success: function(returnedObject) {
console.log('New object created with objectId: ' + returnedObject.id);
},
error: function(returnedObject, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
});
});
Retrieving that info later would be as easy as:
var Message = Parse.Object.extend("Message"); //create a reference to your class
var query = new Parse.Query(Message); //create a query to get stored objects with this class
query.find({
success: function(results) { //"results" is an array, you can fine tune your queries to retrieve specific saved objects too
for (var i = 0; i < results.length; i++) {
var object = results[i];
$(body).append("Message #" + (i+1) + object.get("messageText");
}
},
error: function(error) {
console.log("Failed to complete Query - Error: " + error.code + " " + error.message);
}
});

Is it possible to ping a server from Javascript?

I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).
I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.
If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.
I have found someone that accomplishes this with a very clever usage of the native Image object.
From their source, this is the main function (it has dependences on other parts of the source but you get the idea).
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.
Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.
Update 2: #trante was nice enough to provide a jsFiddle.
http://jsfiddle.net/GSSCD/203/
Update 3: #Jonathon created a GitHub repo with the implementation.
https://github.com/jdfreder/pingjs
Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.
Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:
function ping(host, port, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host + ":" + port, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}
you can try this:
put ping.html on the server with or without any content, on the javascript do same as below:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
You can't directly "ping" in javascript.
There may be a few other ways:
Ajax
Using a java applet with isReachable
Writing a serverside script which pings and using AJAX to communicate to your serversidescript
You might also be able to ping in flash (actionscript)
You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.
You can even calculate the loading time by using onload-event. Here's an example how to use onload event.
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}
Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
There are many crazy answers here and especially about CORS -
You could do an http HEAD request (like GET but without payload).
See https://ochronus.com/http-head-request-good-uses/
It does NOT need a preflight check, the confusion is because of an old version of the specification, see
Why does a cross-origin HEAD request need a preflight check?
So you could use the answer above which is using the jQuery library (didn't say it) but with
type: 'HEAD'
--->
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
Off course you can also use vanilla js or dojo or whatever ...
If what you are trying to see is whether the server "exists", you can use the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This will return a true/false indication whether the server exists.
If you want response time, a slight modification will do:
function ping(url) {
var encodedURL = encodeURIComponent(url);
var startDate = new Date();
var endDate = null;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
if (data.query.results != null) {
endDate = new Date();
} else {
endDate = null;
}
},
error: function(){
endDate = null;
}
});
if (endDate == null) {
throw "Not responsive...";
}
return endDate.getTime() - startDate.getTime();
}
The usage is then trivial:
var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Or:
var responseInMillis = ping("example.com");
alert(responseInMillis);
const ping = (url, timeout = 6000) => {
return new Promise((resolve, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&##/%?=~_|!:,.;]+[-A-Za-z0-9+&##/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => resolve(true))
.catch(() => resolve(false));
setTimeout(() => {
resolve(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
just replace
file_get_contents
with
$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else{
echo "yes!";
}
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

Categories

Resources