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

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!

Related

jQuery .post() to refresh the pages PHP-variables without whiteout in Cake PHP

I got a problem and I´m about to hurt the MVC-paradigm, so I rather ask you what to do.
I got a page which is refreshed every 10 seconds with jQuery .post()-method.
setInterval(function() {
$.post("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?>", { liveUpdate: "true" },
function(response) {
$('#loadingContent').html(response);
}
);
}, 10000);
now, where the "Posts/index" is placed I have to call the PostsController.php of Cake which allows me to reset the variables.
But it doesn´t work that way and the response is filled with all the html of a normal page-call but I only want to have the pure PHP-variables updated without html appended to that div.
What am I doing wrong?
Thanks in advance for your patience.
Since your array is complex multilevel and you do not want to parse JSON, the only way I see doing it would be using jQuery load().
setInterval(function() {
jQuery("#RefreshMeOnPage")
.load("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?> #RefreshMeInResults > *", {liveUpdate: "true"});
}, 10000);
It will make post request to server and replace contents of existing element with id RefreshMeOnPage with the contents of newly received element with id RefreshMeInResults. Docs http://api.jquery.com/load/.
NOTE: Still with refresh rate of 10 seconds, I think you should look into ajax comet solution http://cometdaily.com/maturity.html. It will receive data only when there is change, although it requires some configuration.

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

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);

writing php serverside code for image processing using ajax on frontend. PHP

I have some script that takes a form and sends it to php using jquery ajaxSubmit.
Server side must copy image from one location to another.
using this code copy($img_dir_file,$mini_dir_file); is ok if u have few images.
But if u have let's say 20+ images php works slowly, and responds to ajax before finishing it's job. Thus Ajax changes content to blank page , cause result is not ready.
If you refresh page a bit later, everything is ok cause php finishes his work.
So please tell me what should I do with this problem ?
script is something like this
$('#save_edited_article').live('click',function(){
$('#edited_article_form').ajaxSubmit({
success: function(responseimage){
$('#main_content').html(responseimage) } }); });
You could use a Promise which will inform the browser when the job is complete.
Check out the jqXHR Object as part of Ajax on JQuery - you could then change your main content when the jqxhr object ( which works as a Promise) is complete :
jqxhr.done(function(){ $('#main_content').html(responseimage); });
Edit
An example using your code could be:
$("#edited_article_form").submit(function() {
var jqxhr = $.post(
"foo.php",
$("#edited_article_form").serialize()
);
jqxhr.fail(function(){ alert("fail") });
jqxhr.done(function(responseimage){ $('#main_content').html(responseimage) });
});
Disclaimer : This was written on the fly and may not compile. It is for example purposes only
Have the AJAX call check to see if it's complete, if it's not, keep polling every few seconds until it's ready.
Updated jQuery and ajaxSubmit plugin and everything works nice.

How do I make jQuery notify like Twitter search?

I don't know what it's call. Example
http://search.twitter.com/search?q=%23idontbelieveyou
When you click link above wait a few seconds. Then you will see a notify like this
102 more results since you started searching. Refresh to see them.
There any tutorial for this? Let me know how to make something like that
It's really simple, logically:
A piece of Javascript checks back with the server every n seconds with a timestamp of the latest result it has.
The server checks if any results are available newer than this timestamp and reports back how many there are.
The Javascript displays this notification in the browser.
It would just sent an XHR to the server to see if any more tweets match the query.
If there are new matches, it will return the count and JavaScript updates the DOM to suit.
It is simply polling a script via jquery or Ajax (same thing really)
// Untested, written here without syntax.
var timeSinceUpdate = <?php echo(time()); ?>;
$(document).ready(function(){
setInterval(function(){
$.get('queriesSince.php?searched=idontbelieveyou&timesinceupdate=' + timeSinceUpdate , function(data){
alert(data);
if(confirm('Add new Data to screen?'))
{
//Add Stuff to DOM and update the timeSinceUpdate from the data recieved.
}
});
}, 3000);
});

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