AJAX Updating Javascript Variable from PHP page? - php

I am not a developer so this is new to me, but I am a long time sys admin so please forgive me if I am asking stupid questions!
Basically, I have a PHP script that parses some XML and echo's a single number formatted to 1 dp.
I am using some Javascript Wijmo widgets, in particular a dial that takes it input from a javascript variable. Lets say "resultvalue".
I want to populate "result value" every 5 seconds with the results of my php script that exists as /xmlparse.php. The wijmo widget apparently responds dynamically to a changing variable so this will produce a dial with a moving needle without having to refresh the whole page.
All I need to achieve is getting this javascript variable to update every 5 secs.
I am already doing something similar with AJAX on a html page by just populating a DIV with the results of /xmlparse.php and it works great using the set interval command.
But how can I get my javascript variable updating every 5 secs with the result of that script?
An example would be a great help!
Code Here
Regards
Tom

window.setInterval(function(){
jQuery.ajax({
url:'/xmlparse.php'
}).done(function(response) {
resultvalue=response;
});
},5000);
You'll probably need to parse the result. Perhaps xmlparse should format it with json_encode so your ajax request could grab it as an object.
Edit:
Looking at your source, I see that the radial gauge doesn't actually monitor the resultvalue variable to detect when it's changed. You'll have to update it yourself. In this case:
window.setInterval(function(){
jQuery.ajax({
url:'/xmlparse.php'
}).done(function(response) {
resultvalue=response;
$("#gauge").wijradialgauge({value:resultvalue});
});
},5000);

You can set a global variable and set it as value returned from xmlparse.php;
var resultValue;
// load at page load first
$(document).ready(function() {
updatevalue();
});
setInterval("updatevalue()", 5000);
function updatevalue(){
$.get("xmlparse.php", function(response) {
resultValue = response;
})
}
This is for test
setInterval("test()", 4000);
function test() {
console.log("Result is: " + resultValue);
}

Related

Refresh PHP functions with JavaScript

i need a a script that will refresh the functions:
$ping, $ms
every 30 seconds, with a timer shown,
i basicly got this script:
window.onload=function(){
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds;
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
}
but it refreshes the whole page, not the functions i want it to refresh, so, any help will be appriciated, thanks!
EDIT:
I forgot to mention that the script has to loop infinatly
This here reloads the whole page:
window.location.reload();
Now what you seem to want to do is reload portions of the page, those portions having been generated by php functions. Unfortunately php is server side so that means you cant get the client browser to run php. Your server runs the php to generate stuff that browsers can understand. In a web browser open a page you made using php and choose to view source and you'll see what I mean.
Here's what you'll need to do:
Make your two functions ping and ms accessable via ajax
Instead of window.location.reload() do a call to jQuery.ajax. on success write to your page
Here's what I think would be the ideal way of dealing with this... I haven't seen the php side of your problem but anyway:
make a file called ping.php and put all your ping function code in there. ditto for ms
in your original php file that called those functions, make a div at each point where you wanted a function call. Give them appropriate ids. Eg: "ping_contents" and "ms_contents"
You can populate these with some initial data if you want.
In your js put in something like this:
jQuery.ajax(
{
url : url_of_ping_function,
data : {anything you need},
type : 'POST', //or 'GET'
dataType: 'html',
success : function(data)
{
document.getElementById("ping_contents").innerHTML = data;
}
});
do another one for the other function
What you want is AJAX, Asynchronous JavaScript and XML
You can use jQuery for that.
I can put an example here, but there is a lot of information to be found on the internet. In the past I wrote my own AJAX code, but since I started using jQuery, it's all a lot easier. Look at the jQuery link I provided. There is some usefull information. This example code might be the easiest to explain.
$.ajax({
url: "test.php"
}).done(function() {
alert("done");
});
A some moment, for example on a click on a button, the file test.php is executed. When it's done, a alert box with the text "done" is shown. That's the basic.

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!

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.

Running a PHP script via Ajax, through a link?

I'm making a fairly simple rating system, and I've got a small problem. When you +1 rate something, I'm trying to run a PHP script which will connect to the database, download the value from it, +1 to that value, and UPDATE the value in the database again.
I don't think reloading the page for a continious rating system would be a very good idea :S
I'm wondering how I can toggle a PHP script with Ajax, so that when you Click an image of a + sign, it runs the PHP add 1 script, and the + button turns in to a tick. I'm crap at ajax, and I'd go for trying jQuery + $.ajax({}); but I've failed 73 attempts. haha.
Anyone willing to give me a hand writing an Ajax script? :DDD
Thanks! :)
If you want someone to click a link which will access your page, let's assume you have this marup:
<a class = 'plusOne' id = 'someIDForYourSQLTable'>+1</a>
The ID is what you are going to pass to your server script so you can update the appropriate row, generally speaking this should be a primary identifier (i.e. Key) for the record that you want to +1.
Here is the jQuery that will send the ajax request to the file: plusOne.php in the same directory as the current page:
$(function() {
$(".plusOne").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "plusOne.php",
success: function(data) {
// Whatever you want to do after the PHP Script returns.
}
});
});
});
The request will send the a URL parameter 'v' which you can access in your PHP script from the $_GET super global array.
html
<img src="plusone.png" rel="some_unique_id" class="rate" />
javscript
$(".rate").click(function() {
var elem = $(this);
$.get('/rate.php?id=' + elem.attr('rel'), function() {
elem.attr('src', 'checked.png').unbind('click');
});
});
and in php
mysql_connect('localhost','db_user','pssword');
mysql_query('UPDATE database_name.table_name SET rating=rating+1 where id=' . mysql_real_escape_string($_GET['id']));
Have a look at xAjax, a library to expose PHP functions/method to client-side JavaScript. xAjax makes things very simple.
For example, you are able to perform several changes in the browser in parallel:
$objResponse = new xajaxResponse();
$objResponse->assign("myInput1","value",$DataFromDatabase);
$objResponse->assign("myInput1","style.color","red");
$objResponse->append("myDiv1","innerHTML",$DataFromDatabase2);
$objResponse->prepend("myDiv2","innerHTML",$DataFromDatabase3);
$objResponse->replace("myDiv3","innerHTML","xajax","<strong>xajax</strong>");
$objResponse->script("var x = prompt("Enter Your Name");");
return $objResponse;

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

Categories