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/
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 use this JS to call a PHP file in header.php every second.
$(document).ready(function(){
setInterval(function(){ $('#show').load('m1.php') }, 1000);
})
<div id="show"></div>
In m1, I get data from a database:
$getvalue=mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM users WHERE user_accID=$user_accID"));
$user_value=$getvalue['user_value'];
echo $user_value;
I want to get another data from database for example user_value30 and call this data with setinterval again.
Should I create another m2.php and call it again with same JS?
This way it would be so complex.
Please don't tell me get the all data in m1.php.
I can't because I want to show this data different places in header.php.
I only want a specific division called 'footer' within my home.php file to refresh and display the most recent time update from my database every 30 seconds. I have tried but did not succeed. Can anyone advice how to do?
Here is part of my home.php code:
<div id="footer" style="text-align:right; font-size:0.8em; color:red;">
<?php
echo "Last Update: " .$assignments[0]->time_updated;
?>
</div>
js code:
function getTime(){
$('#footer').load('home.php',function () {
$(this).unwrap();
});
}
getTime();
setInterval(function(){
getTime()
}, 30000);
In this way the value will not be updated, because to get latest value you need to refresh whole page. TO do this, the best way would be
1) First create a PHP file that query db and get latest time,
2) Make ajax request to that PHP file to get the latest time
3) And change the text of the footer.
For example something like following:
$(document).ready(function(){
function getTime(){
//var some_id = $("#some_id").val();// you can get values and pass to your PHP script too
$.ajax({
type: "GET", //or POST how you define your PHP file to get latest date
url: get_latest_date.php,
//data: "id="+some_id, //you can pass some data like this
success: function(msg){
$("#footer").html(msg); //If you just simple echo latest value form your PHP file
}
})
}
getTime();
setInterval(function(){
getTime()
}, 30000);
});
Create a file called get_latest_date.php and simply echo the latest time from DB.
get_latest_date.php
<?php
echo date("H:i:s");
?>
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
i have a text file with a number that is inside it. The number should be +1 inside the text file and the new value should be updated inside index.php all this should happen after a button inside index.php is clicked, but thats not happening.. i did a lot of googling and i tried many things from what i sow still it's not working, keeping in mind I'm new to jQuery. below is all the involved code explained. any help will be appreciated!
The php script inside index.php to retrieve the value from num.txt and place it inside the text input once index.php is loaded, this works perfectly:
<?php
$filename = "num.txt";
$file = fopen("num.txt","r+");
$number = fread($file, filesize($filename));
fclose($file);
?>
The text input code, as you can see will take the $number value from the above script and this works fine. keep in mind i used the id of the input and the class of it then i ended up adding a div and using its class, i didn't know what to do so i tested them all, same thing nothing worked:
<div class="on"><input type="text" id ="omlat" class="inv-number" value="<?php echo $number;?>"></input></div>
jQuery to update the value after clicking on the submit button. this function should only refresh the value of the input value by calling inum.php and taking the value inside inum.php after the code there is excited:
$(document).ready(function(){
$(".reloadpg").click(function(){
$(".on").load("http://localhost/einvoice/inum.php");
});
});
Code inside inum.php, this code works fine i tested it (this code takes the number inside num.txt and +1 the value as you can see):
<?php
header("Cache-Control: no-cache");
$filename = "num.txt";
$file = fopen("num.txt","r+");
$number = fread($file, filesize($filename));
$number = $number + 1; //the new number to proceed
file_put_contents('num.txt', $number);
echo $number;
fclose($file);
?>
-- Update --
The code bellow worked for the above part it worked perfectly but now I'm facing another problem. Another function that listens to the same button that was working before stopped working! so what i did was that i toke some of the code that the guys bellow provided and pot it inside the older function that was listening to the button click the whole code is as follows(please read the comments to understand the code):
$('.create-invoice').on('click',function()
{
//Below is the code i added from the first problem above its not working here.. when it was alone outside this function as the accepted answer it will work but it will stop this function from working!
$.get( "/einvoice/inum.php", function(data) {
$('.inv-number').val(data);
});
//Above is the code i added from the first problem..
//below is the original code for the function, keep in mind only the below code is bing excited the above is not.. its not refreshing the part of the page it should its calling the php script successfully tho, but i will have to refresh the page my self to see the number updated
grab_invoice_data();
// Declare a variable
var jsonObj = invoice_data;
// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);
// Lets put our stringified json into a variable for posting
var postArray = {json:postData};
$.download("php/json.php", postArray, 'post');
//if cookie exists
var i_n = $('.inv-number').val();
$.cookie('lid', ++i_n, { expires: 365 } );
//invoices created
if( $.cookie('ic') ){
var ck_inv_created = ($.cookie('ic'));
$.cookie('ic', (++ck_inv_created));
} else {
$.cookie('ic', ++inv_created);
}
})
You're replacing the input with the number, rather than just updating its value. Try this instead...
$(document).ready(function(){
$(".reloadpg").click(function(){
$.get("http://localhost/einvoice/inum.php", function(data) {
$(".on input").val(data);
});
});
});
That uses jQuery's get() method to make an ajax call that passes the response into a callback function as a parameter. You can then do whatever you need with it inside that function.
You jquery part is not good. Try this :
$(document).ready(function(){
$(".reloadpg").click(function(){
$.get( "/einvoice/inum.php", function( data ) {
$("#omlat").val(data);
});
});
});