Refreshing html via javascript and php - javascript

I'm trying to show a notifications counter updated upon javascript.
I have tried to use the following to refresh the html:
At the top of the page declaring the counter value (how many messages user has):
<?php
$nc = notificationCount($user_data['id']);
$ng = $user_data['id'];
if ($nc >= 1){
$nstyle = 'style="display:block;"';
} else {
$nstyle = 'style="display:block;"';
}
?>
Then the standard initial loading of the counter value that works properly:
<li id ="ndiv" class="nav-item pt8" <?php echo $nstyle; ?>><a href="javascript:void(0);" data-toggle="modal" data-target="#myModal" onclick="showUser(<?php echo $ng;?>)">
<i class="fa fa-bell f18 cr"></i><span id ="nc" class="f16 cr"><?php echo $nc;?></span></a>
</li>
In attempt to keep the counter refreshing every 5000 I tried the following, but it does not refresh despite the increase in value taking place.
<script>
function checkNotification() {
console.log(' each 5 second...');
document.getElementById("nc").value = "<?php echo $nc;?>";
}
var myVar = setInterval(checkNotification, 5000);
</script>

A PHP page returns a result to the client. Once the page returns its result, it's done. You can't have a PHP page return a result every so often. But, what you can do is call out to a PHP page (using AJAX) that returns the notification count at regular intervals using setInterval().
let notifications = document.getElementById("notifications");
// This would be a function that calls a .php page to get
// the notification count returned. You could use AJAX
// to make that call.
function simulateServerCode(){
return Math.floor(Math.random() * 100);
}
let timer = setInterval(function(){
notifications.textContent = simulateServerCode();
}, 5000);
<div>You have <span id="notifications"></span> notifications.<div>

You don't need the server side for showing the notifications.
Try this:
JS:
notificationsCount = document.getElementById("notificationsCount");
numberOfNotification = 10; // example
showing = setInterval(function(){
notificationsCount.textContent = numberOfNotificaton;
}, 5000);
HTML:
<h1>
Number of notifications <h1 id="notificationsCount"></h1>
</h1>

Related

Refresh Button when clicking on it

I got a button which i want to reload on click. But only the button should be reloaded, not the rest of the page.
The button looks like this:
<a href="{$module_data.GM_PRODUCTS_BUTTON_BUY_NOW_URL}" id="click{php}echo ''.$counter.'';{/php}" class="addcart button_green button_set action_add_to_cart"{if $module_data.PRODUCTS_NAME != ''} title="{$module_data.PRODUCTS_NAME|replace:'"':'"'} {$txt.text_buy}"{/if}
onclick="return checkAddToCart(event, '{$module_data.QTY_DATA.ID}', {$product_stock}, {$product_max_order}, {$module_data.PRODUCTS_ID}, {php}echo $row['customers_basket_quantity']{/php}, {php}echo "'click".$counter."'";{/php});">
<span class="button-outer">
<span class="button-inner">{$button.add_to_cart}</span>
</span>
</a>
Now i told javascript that echo "'click".$counter."'"; is the clickid.
I tried the following thing to reload my page on click:
function checkAddToCart(event, tid, stock, maxallowed, pid, pquantity, clickid)
{
var clickid_string = clickid.toString();
var bought = Number($("#"+tid).val());
stock = Number(stock);
maxallowed = Number(maxallowed);
var ans = (bought>stock) || (bought > maxallowed);
if(ans)
{
event.stopPropagation();
event.preventDefault();
alert("Maximale Bestellmenge: " + Math.min(maxallowed, stock));
}
else {
$("#"+clickid_string).load("#"+clickid_string);
}
return !ans;
}
It is not working, and i have absolutly no idea why. By the ay, my system works with SMARTY tpl.
If you want to run a php script on click of a button you need to learn ajax. Ajax its just a simple way to use javascript, to run pages in background without reload the current page.
<span class="button-outer" onClick="addDataToDB(this);">...</span>
<script>
function addDataToDB(el) {
var elem = $(el);
/* GET ALL YOUR DATA*/
var name = ...
/* Create an AJAX request to your phpfunction */
}
</script>
Check some tutorials in youtube.

how to use javascript pass value to php or txt file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
<?php
$myFile = "new.txt";
$fileOpen = fopen($myFile, 'w') or die("can't open file");
$stringData = "total;
fwrite($fileOpen, $stringData);
fclose($fileOpen);
?>
<html>
<head>
<script>
var defaultValue = 5;
var plus = 1;
var max = 100;
var total = defaultValue;
window.setInterval(
function () {
if (total > max){
total = defaultValue;
}
document.getElementById("demo1").innerHTML = total;
total = total + plus;
}, 1000);
</script>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</body>
</html>
I need save the total value into txt file, and than read by txt. so that, when i refresh the browser will not re-looping, but how i get value from javascript or from div into php? (read and write per second)
You can use an AJAX request to a php file where you can save it to txt file or a database.
But, making an ajax call every second would be unnecessary traffic. Instead I think using window.onunload would be a better choice, which saves the value when the page is redirected or refrshed.
You can use the jquery bind for that as below:
$(window).bind('beforeunload', function(){
// make ajax call here
});
If you want to save very small amount of data, like here you need to save the value of total then you can use HTML 5 provided local storage which can easily contain on average 5 MB of data. Its nothing but a storage in each domain(origin) which can store 5 MB on any individual client.
It is very easy to use like.
enter code here
// Store
localStorage.totalValueHolder = total;
// Retrieve
var totalStringValue = localStorage.totalValueHolder;
total = parseInt(totalStringValue, 10)
OR
// Store`enter code here`
localStorage.setItem("totalValueHolder ", total);
// Retrieve
var totalStringValue = localStorage.getItem("totalValueHolder");
total = parseInt(totalStringValue, 10)
Hope it will answer your question. If you have further query please let us know.

Counter in Javascript closure not incrementing

I am writing some JavaScript code, where I am using a closure for a counter. The code is given below:
function userHandler(){
var counter = 0;
var limit = "<?php echo ($_SESSION['limit']); ?>";
return function(){
var args = {
n : $('#name').val(),
s : $('#ssn').val(),
i : $('#id').val()
};
$.post("adduser.php",args,function(data){
var response = JSON.parse(data);
console.log(args);
if(response.status == 0){
counter += 1;
alert(counter);
if (counter == limit){
$('#limit').text(limit-counter);
}
}
console.log(data);
});
};
}
var opcall = userHandler();
$('#addUser').on("click", opcall);
I am using this guide to write the code. The problem is, my counter always shows 1 in the alert box. It does not increment. Am I not calling the inner method correctly?
EDIT: There's a span in the HTML which is receiving the limit-counter value:
<p>
<span>Add User</span>
You can add <span id="limit"></span> more users. <a href='<?php echo $root; ?>editaccount.php?action=addOp'>Add another operator?</a>
</p>
It always shows (20-1)=19 every time I submit the form which uses the Javascript.
UPDATE: Thank you for pointing out my mistake, after clicking the "addUser" button, another page was opening with a confirmation message, where a link had to be clicked to return to the original page. I moved the confirmation message to the original page and now it works fine!!

Refresh part of my php page with setInterval()

I have a value on my PHP page and I want to refresh it per second with setInterval().
So I actually know how to refresh values with html etc. But now I want to do the same with php values. Here is my code:
<script>
setInterval(function()
{
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
},1000);
</script>
Ofc this isn't working since JS and php arent really great together.
and in my table I just simply have:
<table>
<tr>
<td>Activity:</td>
<td><p id='MachineActivity'></p><?php echo $TimeMachineActive; ?></td>
</tr>
</table>
So the problem now is, it's only refreshing when I press f5. But now I want the autorefresh. I know setInterval() worked for html. Is it possible to get this done for php code?
This should work for you:
JS Code:
<script>
setInterval(function()
{
$.ajax({
url: 'value-generation.php',
type: 'get',
success: function(response){
$("#MachineActivity").html(response)
},
});
},1000);
</script>
value-generation.php code:
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
echo $TimeMachineActive;
?>
This is how you convert php value to javascript value
<script>
setInterval(function(){
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
var n_val = "<?php echo $TimeMachineActive; ?>";
console.log(n_val);
},1000);
</script>
Change console and give it to your desire.
But does this make the loading time more ? Every second you are calling a remote page and checking ?
When you refresh, PHP returns the whole page again, and it cannot refresh parts of the page. So if you want just part of the page refreshed, you'll need to use iframes.
<body>
<h1>This is my main PHP page</h1>
<iframe src="[url-to-another-php-page-with-only-the-timer]"></iframe>
</body>
And then you'll have to do a separate php page with just the timer value, and serve the html with a meta tag - this meta tag will do the refresh. Meta tag is detailed in this ticket: PHP - auto refreshing page
You need to define setInterval function.
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Now call your set interval function and it should work fine.
As you know, a PHP file will make the server generate a page when you call its URI.
The way you are using your script won't make the server "regenerate" the page and update the values.
Assuming this, you can:
Externalize the php code which is in your setInterval function (ex: update_time_machine.php)
Recall the externalized PHP resource(using IFrame or a request)
Update your page through Jquery/JAVASCRIPT using the PHP script output.
Edit: Mihali's answer sounds the cleanest one.
I'm sure this will work for you
<script>
setTimeout(function(){
location.reload();
},1000); // 1000 milliseconds means 1 seconds.
</script>

Javascript Variable in Ajax Updater

I am trying to send the javascript variable 'sortlist' to an Ajax function using the following code:
<div id = "output">Drag to sort</div>
<script type="text/javascript">
var session = <? echo $sesh; ?>;
var track = <? echo $trk; ?>;
var sortlist = "sortlist_" + session + "_" + track;
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
})
</script>
The variable appears to be passing successfully to Sortable.create (because I can sort the boxes on the webpage), but it does not appear to be passing into Sortable.serialize within Ajax.updater (because it no longer writes the sort order values to the database).
This code works when I use the literal value in Sortable.serialize, like
parameters:Sortable.serialize('sortlist_1_1'),
I have tried using sortlist as a variable with and without single and double quotes inside Sortable.serialize to no avail. What is the format required to successfully pass this variable information?
For reference,
My AJAX/javascript experience is about a 1 (scale 1-10); my PHP/MySQL experience is about a 7 (scale 1-10).
Try this:
Sortable.create(sortlist,{
onUpdate:function(sortlist){return function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
};}(sortlist);
})
Let's go one step further then:
function(sortlist){
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
});
}(sortlist);

Categories