visual traceroute similar "yougetsignal.com", how to update div on demand/periodically - php

this is my first question in a forum ever i think ;-).
I will try to be as clear as possible with the question.
I´m trying to build a visual traceroute similar to that on yougetsignal.com by kirk ouimet.
It is actually working already using bash (traceroute,ping,host,) php/javascript, but I´m having some trouble with Javascript/AJAX.
Kirk updates the traced host-list periodically or via some kind of ajax-interrupt on the right side of the trace. I only know how to do it in one pass with one single Javascript xmlhttp-call and then echo a table into a standard w3school-livesearch-DIV.
http://www.yougetsignal.com/tools/visual-tracert/
I also don´t know if he does the traceroute with a cmd-line-tool like linux´s "traceroute".
Mine is working fine by first tracerouting, then doing reverse-lookup using "host" and then
pinging all hosts in the list again to get the rrt.
Is there any way to poll a txt-file (the traces) and then echo the output on demand to
a DIV?
I´m grateful for any hint.
Stefan
p.s.: the google-maps plotting works fine, it´s about the process of updating the traced-hosts
on demand for users (and me) to enjoy.

What you can do by using jQuery for ajax calls:
setInterval(function () {
$('#yourdiv').load('http://domain.com/yourfile');
}, 30000);
This code will load pregenerated html content to a specified div container every 30s. If you don't what to load a temporary generated html/php content, you can build an API and then add the data comming back dynamically on the DOM every time.
setInterval(function () {
$.getJSON('yourAPIUrl', function (data) {
$.each(data, function (item) {
// do something with the retrieved data, add it to the DOM for example
}
});
}, 30000);

Related

Using RGraph to poll data from a Postgres DB and update using AJAX/JSON

I'm a bit out of depth on this one so I hope someone has some insight. :)
I'm attempting to update a div using AJAX. The AJAX call sends a dropdown selection's value to a PHP file, which will be performing a pgsql query to grab some data. I've read in the RGraph tutorials that this data needs to be formatted to a JSON format so that RGraph can interpret it, and then fed to the JS that runs the RGraph views.
This question might actually be 2 separate questions, but I'll ask anyway:
Is there a standard way to grab the query's results in PHP and output them into a JSON format?
Where would I want to trigger the JS that uses the JSON data? I've tried hardcoding some initial data but the graphs don't seem to show up. However, I know the jQuery is performing the AJAX calls correctly because I see the div update (with an in-between "Loading..." message and then back to blank, indicating to me a null response), so I think I'm just not scoping this properly.
P.S. No, this time I'm not making a $_POST/$_GET mistake.
Any help would be appreciated. Thanks!
EDIT 1: Got this one. It was actually way easier than I thought. Still not scoping properly, however. Any help with how RGraph grabs a JSON object and displays it as a graph, and how to use AJAX to refresh the div with a new graph?
There's some SVG based AJAX demo pages here:
There was a bunch of links to the SVG basic AJAX demos here, but now the demos are no longer online - they are in the download archive. So download it here: https://www.rgraph.net/download.html#stable
There's a JSON documentation page here:
https://www.rgraph.net/svg/docs/the-svg-ajax-functions.html
And the code example from it is this:
<script>
GLOBALS = {};
function draw()
{
RGraph.SVG.AJAX.getJSON('/ajax/getdata.html?json', function (json)
{
if (GLOBALS.bar) {
RGraph.SVG.clear(GLOBALS.bar.svg);
}
GLOBALS.bar = new RGraph.SVG.Bar({
id: 'chart-container',
data: json.data,
options: {
// Add your own options to configure the chart
}
}).draw();
});
}
draw();
</script>
If you follow this example, create a page on your website that gets the data from your database and outputs it like this page does:
https://www.rgraph.net/getdata.html?json
Note that there's no HTML output by that page - just the JSON.
Then you can fetch that page using the RGraph.SVG.AJAX.getJSON() function like the code above does - from your webpage that has the chart on it - eg foo.html
So the foo.html is what would contain that RGraph code above.
And if you wanted it to repeat then you could add a timer so that subsequent fetches update it:
setTimeout(function ()
{
draw();
}, 1000);
I think that covers everything. I've probably left something out though.

How to display a 'live' count of total files uploaded?

I am looking to display the total number of files in a database. To clarify, say I had a website where people could upload pictures of their cars, and I wanted to display a live number of how many pictures there are, what would be the best way to do this? Javascript, php? A mix? I envision a div with a number saying "Total Pictures: x" and where x would be whatever the live total is. I plan on using MySQL to store all the data on the website. Is this even recommended to have something communicate with the server this much? Is there a name for displaying a live number? Thanks!
If you are thinking to use the AngularJS way, you could create a Poller service which polls every second (assuming your /counter.php returns json):
app.factory('Poller', function($http, $timeout) {
var data = { response: {}};
var poller = function() {
$http.get('/counter.php').then(function(r) {
data.response = r.data;
$timeout(poller, 1000);
});
};
poller();
return {
data: data
};
});
Then your controller:
app.controller('CounterCtrl', function(Poller, $scope){
$scope.counter = Poller.data;
});
And finally in your view:
{{counter.response}}
You can read more about $http
Set up a PHP script that queries the database and returns the total file upload count. After that, you can use JavaScript on the page to periodically call the server in a specified interval of time and fetch the count data from your PHP script. Using jQuery and GET, you can do something like this:
jQuery(function($){
setInterval(function(){
$.get( '/counter.php', function(fileUploadCount){
$('#counter').html( fileUploadCount );
});
},20000); // 20 seconds
});
In your HTML:
<p><span id='counter'>xx</span> files have been uploaded so far!</p>
Hope this helps!
How live do you want it to be? Just whenever someone updates the site it's going to have the new value or do you actually want it to update in near real-time?
If it's the latter you have to use Javascript against some kind of API that returns the amount of files in the database. I can't help you with that bit since you are using PHP, but it shouldn't be too hard. Just return some JSON looking something like
{ fileCount: 45020 }
Client-side you have a few options. You have the different javascript frameworks like AngularJS and EmberJS (and many more), as well as just 'plain old' javascript and frameworks like jQuery
The keyword is really AJAX, even if that is just a sort of buzzword for using javascript to make websites dynamic.
I am a fan of using AngularJS because it's easy, but I'll try to give you some pointers for using jQuery first. Note that I have not used jQuery in years now.
The jQuery way
jQuery has a function called jQuery.getJSON(), and according to the documentation you can use that function something like this:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "http://example.com/api/fileCount.json")
.done(function(data) { console.log(data) })
.fail(function() { console.log( "error" ); })
.always(function() { console.log( "complete" ); });
So this means we can call an endpoint and fetch some data using jQuery.
Here is a link to a tutorial about the basics of jQuery by the way.
jQuery makes us able to do things like this:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
When that is executed the div with id "divTest1" will contain the text 'Hello, world!'.
That sounds like something we could use here!
Javascript also has this really nice function called setTimeout(), which allows us to make it call a function later.
This describes how to use jQuery with setTimeout()
As you can see it also shows us jQuery.documentReady(), which is an event that fires when the website is finished loading, so it is a good place to put code we want executed.
The example below shows how to use jQuery to hide a div with id=div after 3 seconds.
jQuery(document).ready(function () {
setTimeout( "jQuery('#div').hide();",3000 ); //hide a div after 3 seconds
});
Combining these things you should be able to make a repeating call that fetches data from your server and then updates a div or another element with the data you have fetched.
Just create a function which uses jQuery.getJSON() to fetch data, and then at the bottom of that add a setTimeout call to run itself in X seconds (however often you want it to update).
In jQuery.documentReady() you call that function the first time the document loads.
And in the .done() bit of the getJSON() call you add the data you got from the server to your div with whatever html you want. I showed you how to use $("#divTest1").text(), but there is also a .html() which acts the same but you should use it to add html to a element.
The angular way would be to use AngularJS's $http to do the same thing, but I wouldn't recommend learning AngularJS until you have a bit of a better grasp on Javascript.
When you do though, I highly recommend it. It's a much better approach than using jQuery.
You can read about AngularJS here
I hope this helps!

Loading pages with dynamic content

I've been working on a project for a couple of Minecraft servers that use Bukkit. I'm trying to create a web page that contains a dynamic map of the servers' worlds, as well as a real-time event update system, where a <div> is updated as events happen on the server. To give a brief outline of how my system works, the Minecraft servers communicate events with a Node.js webserver over the same network via UDP packets, and the Node.js webserver uses these packets to build JavaScript objects containing the event info. The objects are then stored, and passed to Jade whenever the page is requested. Jade takes care of the templating.
What I want to do is update this page dynamically, so that the user doesn't have to refresh the entire page to update the list of events. What I'm trying to implement is something like the Facebook ticker, which updates every time a Facebook friend does something like posting a status, commenting on a post, or 'liking' a post.
In reading this question on SO, I've concluded that I need to use long polling in a PHP script, but I'm not sure of how to integrate PHP with a webserver written almost entirely in Node.js. How could I go about doing this?
EDIT:
I've run into a problem in the clientside code.
This is the script block:
script(src='/scripts/jadeTemplate.js')
script(src='/socket.io/socket.io.js')
script(type='text/javascript')
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement("item");
jade.render(newsItem, 'objTemplate', { object: obj });
$('#newsfeed').prepend(newsItem);
console.log(obj);
alert(obj);
});
And this is objTemplate.jade:
p #{object}
// That's it.
When the alert() and console.log() are placed at the top of the script, it alerts and logs, but at the bottom, they don't execute (hence, I think it's a problem with either the creation of newsItem, the jade.render(), or the prepend.
If I need to provide any more snippets or files let me know. I'm still tinkering, so I might solve it on my own, but unless I update, I still need help. :)
I'd skip PHP and take a look at socket.io. It uses websockets when possible, but it will fall back to long-polling when necessary, and the client side library is very easy to use.
Whenever your node.js server has a new object ready to go, it will push it to all connected browsers. Use ClientJade to render the object using your template (you may have to break out the relevant part of the main template into its own file), then prepend the generated dom element to your feed.
First, if it isn't this way already, you'll need to break out the relevant part of your jade template into its own file. Call it objTemplate.jade. Then use ClientJade to create a compiled template that can be run in the browser: clientjade objTemplate.jade > jadeTemplate.js. Put jadeTemplate.js in your public js directory.
In your node.js app, you'll have something like this (pseudo-codey):
var io = require('socket.io').listen(httpServer);
listenForUDPPackets(function(obj) {
saveObjSomewhere(obj);
io.sockets.emit('obj', obj);
});
Then on the client, something like this:
<script src="/js/jadeTemplate.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement();
jade.render(newsItem, 'objTemplate', obj);
$('#newsFeed').prepend(newsItem);
});
</script>

Correct or best process for loading PHP files and displaying the status using jQuery/Ajax/JS

So i'm working on a project that will be using PHP to download files with CURL and update them on the server. I've already gotten that part taken care of and now i'm working on a front end gui that will display the progress to the user.
So my original thought method was to use the code in this manner:
$('#startupgrade').click(function() {
$('#upgradeprogress').css({"width": "0%"});
$('#upgradestatus').append('<p>Starting Upgrade...</p>');
$('#upgradeprogress').css({"width": "10%"});
$('#currentstep').load('upgrade.php #statusreturn', 'step=1');
$('#upgradestatus').append('<p>Step 1 Complete...</p>');
$('#upgradeprogress').css({"width": "20%"});
})
The thought behind this was to load the PHP page and pull a "status message" from the page which PHP generates in the ID #statusreturn which would then be appended to the current page if that step fails or is successful. In the example above I kept it simple and just went ahead and appended Step 1 Complete but i would add some type of standard JS in there to check if the first step was completed or not.
I've very new to JS and jQuery and I feel like there should be an easier or more correct way of doing this. Maybe running some standard JS using an if statement based on the number of steps?
Does anybody have any suggestions or recommendations on how this could be done with less code or in an easier manner? I want to make sure the method I end up using and learning will be correct and hopefully i'm not making newbie mistake and using more code than is necessary.
I appreciate any input and thanks for your help in advance.
The #upgradeprogress is using Twitter Bootstrap progress bar which is controlled by the width. The #upgradestatus is a Bootstrap well that will display the output almost similar to a terminal.
The load function is an asynchronous function. That means it will directly continue and not wait for the load. In order to wait for the load place your update of progress bar into the success callback handler:
http://api.jquery.com/load/
$('#result').load('steps/step1.php', function() {
$('#upgradeprogress').css({"width": "10%"}); //update your status bar here
$('#currentstep').load('upgrade.php #statusreturn', function() {
$('#upgradeprogress').css({"width": "20%"});
//add more steps here if required
});
});
Only when that success function( ) is executed you can be sure the request was finished.

AJAX calling a PHP code and getting a response every few minutes

I'm trying to create a very simple message board (author, text, and date written) that will auto-update every few moments to see if a new message has arrived, and if it has, auto load the latest message(s).
I'm proficient in PHP, but my knowledge in AJAX is lacking.
The way I see it, I would have to create a PHP file called get_messages.php that would connect to a database and get through a $_GET variable return all posts beyond date X, and then I would somehow through jquery call this PHP file every few minutes with $_GET=current time?
Does this sound correct?
How would I got about requesting and returning the data to the web page asynchronously?
You're pretty close, you'll need a PHP script that can query the database for your results. Next, you'll want to transfigure those results into an array, and json_encode() them:
$results = getMyResults();
/* Assume this produce the following Array:
Array(
"id" => "128","authorid" => "12","posttime" => "12:53pm",
"comment" => "I completely agree! Stackoverflow FTW!"
);
*/
print json_encode($results);
/* We'll end up with the following JSON:
{
{"id":"128"},{"authorid":"12"},{"posttime":"12:53pm"},
{"comment":"I completely agree! Stackoverflow FTW!"}
}
*/
Once these results are in JSON format, you can better handle them with javascript. Using jQuery's ajax functionality, we can do the following:
setInterval("update()", 10000); /* Call server every 10 seconds */
function update() {
$.get("serverScript.php", {}, function (response) {
/* 'response' is our JSON */
alert(response.comment);
}, "json");
}
Now that you've got your data within javascript ('response'), you are free to use the information from the server.
Ignore the ASP.NET stuff, this link is a good start:
http://www.aspcode.net/Timed-Ajax-calls-with-JQuery-and-ASPNET.aspx
What you're going to use is a javascript function called setTimeout, which asynchronously calls a javascript function on an interval. From there, jQuery has a fancy function called "load" that will load the results of an AJAX call into a DIV or whatever element you're looking for. There are also numerous other ways to get jQuery to do alter the DOM the way you'd like.
There are a hundred ways to do this, but I'd say avoid writing plain Javascript to save yourself the headache of cross-browser functionality when you can.
I suggest you go for the Simple AJAX Code-Kit (SACK) available on Google code.
I've been using it since before it was on Google code. It's very light and straightforward. It's one js file that you have to include. I've seen it being used in online browser games as well.
http://code.google.com/p/tw-sack/
Example for loading page contents from get_messages.php in a div (if you don't care about the page contents from get_messages.php, and simply want to call the php file, simple remove the ajax.element line):
<script type="text/javascript" src="tw-sack.js"></script>
<script>
var ajax = new sack();
ajax.method = "GET"; // Can also be set to POST
ajax.element = 'my_messages'; // Remove to make a simple "ping" type of request
ajax.requestFile = "get_messages.php";
ajax.setVar("user_name","bobby");
ajax.setVar("other_variables","hello world");
ajax.setVar("time",dateObject.getTime());
ajax.onCompleted = whenCompleted;
ajax.runAJAX();
function whenCompleted(){
alert('completed');
}
</script>
<div id="my_messages">Loading...</div>
You don't need to specify an "ajax.element" if you want to do a simple "ping" type of request and ignore the output of the php file. All you have to do to implement your requirements now is to use a "setTimeout" making the ajax calls.
There are also many other options like:
//ajax.onLoading = whenLoading;
//ajax.onLoaded = whenLoaded;
//ajax.onInteractive = whenInteractive;
No need to learn or include huge frameworks. And you'll get started in no time with tw-sack.

Categories