I have this PHP function called GetTotalItemsPercentage() which gets the amount of entries in my MySQL database and returns a percent based on the maximum amount of entries that are allowed (returns 50, 40, 39 etc.). However, I want this to update a div's height depending on this percentage. I currently have this code, however after the first update, it doesn't update again.
<script type="text/javascript">
setInterval(function() {
$("#filled-jackpot-display").animate({height:'<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>%'});
}, 2000);
</script>
So how would I go about getting it to update every two seconds and constantly change the size of the div? I'm guessing I will have to run a loop in the PHP code and then use echo inside the PHP file to run JavaScript rather than the other way.
PHP executes on server, javaScript on the client, you have to make a new php file with
<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>
in it, let's call it 'getTotalIP.php' then you call it with ajax.
<script type="text/javascript">
setInterval($.ajax('getTotalIP'), 2000); //Short answer with jQuery
</script>
If your script is intended to print something then you need more code to parse the answer. A good way to do it is printing the php result in json and parse it with javaScript.
Here you have more cross-browswer ajax information: https://www.w3schools.com/php/php_ajax_php.asp
You cannot execute PHP on the client side. The way to do this would be to call the php code with ajax() and then animate in the success handler
myscipt.php
<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>
myscript.js
setInterval( function() {
$.ajax({url: 'myscript.php', success: function(data){
$("#filled-jackpot-display").animate({height: data});
}, 2000);
Note, since ajax is asynchronous, it may not smoothly animate in 2 second intervals. If you only need the height once, then load it on ready and proceed to animate in 2 second intervals
Related
When doing ajax/jquery I normally use the below code to achieve that and it works perfectly fine. To explain what happens below it basically calls the commentS.php script and outputs the data where the id equals to the fieldID and to check for those results every 3 seconds and output the results within the div tags.
<div id="content"> </div>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#content').load("commentS.php?id=<?php echo $fileId; ?>")
}, 3000);
});
</script>
HOWEVER I have several different outputs I would like called and wanted to find out if there was a simplified way to achieve it.
Like I have this line
$delstoriesbyadmin = mysql_query("SELECT count(*) FROM story WHERE deletedby !='0'");
<?php echo mysql_result($delstoriesbyadmin, 0); ?>
I'm asking is there a way in ajax/jquery instead of having an external file with the script just run the mysql query within the call and output the results and have it run that call every 3 seconds. (without the use of an external file). I am new to ajax/jquery. Just want to know if that I want to achieve is possible.
thanks for your answers.
I think you need to do Ajax request nested of load the file....this
solution for your case is build an action page thats return needed
result every request
Ajax Example:
$.ajax({url: "commentS.php", data: {"id": yourId},success: function(result){
// do somthing with success result...
}});
PHP:
$delstoriesbyadmin = mysql_query("SELECT count(*) FROM story WHERE deletedby !='0'");
echo json_encode(mysql_result($delstoriesbyadmin, 0));
In php you need to return data as a JSON type.
Note: if you need to do something every time, and its like get any update comment or something like this behavior, you can use a socket.io for that.
I would create an ajax code that load a php page every x seconds.
Result: obtain a specific php var in the loaded page.
Then: assign the value of the obtained var to a javascript.
Polling, in your case downloading a page every x seconds, is hardly ever the best approach to a problem. It wastes resources.
However, if you want to do something with Ajax, I suggest you use JQuery:
https://api.jquery.com/jquery.get
An example, suppose you have a php 'test.php' file with:
echo $myVariable;
You can then do this in javascript:
$.get("test.php", function( data ) {
alert( "The PHP variable is: "+data);
});
Combine this with a Javascript timer and you're done.
I am populating a js array thanks to php every 2 seconds but it works only the first time because the php code is executed only when I open the window but I want to execute it every time I launch the js function.
Here is my code :
function update(){
var datas = <?php echo Gallery::getPhotos(); ?>;
...
}
setInterval( "update()", 2000 );
The problem is that the var datas never changes because <?php echo Gallery::getPhotos(); ?>; is executed only the first time. How can I do to execute the php every 2 seconds ?
I saw solutions with doing a request on a file but I don't know how to do and I don't know if this is the solution for only 1 instruction.
Gallery is a singleton class which stores pictures, the function getPhotos() returns an array with photos names.
As the <?php ... ?> is only run on a page load, you may have to use AJAX. Below is a rudimentary example:
EDIT: Heres a working example:
setInterval(function(){
$.get("myphp.php",function(data){
update(data);
});
},5000);
function update(data){
//...
}
Reference: http://api.jquery.com/jQuery.get/
I'm updating my php page each 5 seconds
window.setInterval(function(){
console.log(<?=mysql_num_rows(mysql_query("select * from records"))?>)
}, 5000);
If I have 5 records in my table, the output will be 5,
but when I insert a new record, the output remains 5 unless I refreshed the whole page, then it will be 6..
What's wrong?
You have a fundamental misunderstanding of how PHP and Javascript work. Don't worry, it's very common when first learning web development!
When you use PHP to print things onto the page (for example the code inside <?= ?>), the code is executed on the server. Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
This means that when your Javascript loop runs, it's simply writing out the same precomputed value repeatedly.
To accomplish what you're going for, you'll either need to accept simply refreshing the page every 5 seconds, or read up on AJAX. AJAX is how you can load new content from the server (so, anything from the database) without reloading the page. It's what StackOverflow uses to show "1 new answer to this question", for instance.
This is because you are mixing PHP with JS, PHP value is written on page load and it remains that for all the time you stay in the page.
You should use a Ajax request that request again the value.
Do a PHP page that only returns this value:
<?=mysql_num_rows(mysql_query("select * from records"))?>
Then extend you JS with something like this:
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000);
You need also to include Jquery to do this
you can not use php in javascript codes
you soulde save php in example.php and you call example.php in javascript code
your example.php like this
<?php
echo mysql_num_rows(mysql_query("select * from records"));
?>
and you can now get data from example around 5 second time by this code (load is jquery function)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
setTimeout(function(){
$("#showRes").load("example.php");
}, 5000);
</script>
</head>
<body>
<div id="showRes"></div>
</body>
</html>
you are normally mix the concept of jaavscript and php .you can solve this very easily . by passing php value into ajax and that value u should catch in that javascript .Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
write php code in php page like:-
<?=mysql_num_rows(mysql_query("select * from records"))?>
and use js as different page . call that value as your requirement.
like:--
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000)
if u need some jquery then you also include that in your code .
I have a problem with passing JS-defined Variables from an AJAX response to a JS-API, namely Googles jsapi. What I want to do is display a chart using this API and then use AJAX from time to time to reload the values from a database.
So far, everything works just fine. But as I return these variables by AJAX - how can I get JS to parse the result?
The code:
<div id="t">
xyz
</div>
<script>
window.setInterval(function()
{
$.post('mod/script.php', function(data) { $('#t').html(data) } );
}, 5000);
</script>
Where script.php would return values like
echo "data.addRows($datasets);";
echo "data.setValue($i, 0, '$date $time');";
Problem is, that I dont know, which values are returned by the script. This depends on what is currently stored in the database.
How to do this right? I have some ideas, but I wonder what is the most convenient way here...
If I get you right, you want to execute certain JS callbacks in the context of the current document, is that right?
The proper way would be JSONP.
A really really really quirky "alternative" would be to do this in your script.php:
echo "(function(){";
echo "data.addRows($datasets);";
echo "data.setValue($i, 0, '$date $time');";
echo "})()";
and have this callback:
$.post('mod/script.php', function(callback){ eval(callback); });
Also, see this fiddle: http://jsfiddle.net/EsytA/1/