js counter not displaying in php - php

I do not understand why I am not seeing each number diaplyed in the div.
My code...
<head>
<script>
function countit(i)
{
document.getElementById('counter').innerHTML = i;
}
</script>
</head>
<body>
<div id="counter"></div>
<script>countit(1)</script>
<?php sleep(1); ?>
<script>countit(2)</script>
<?php sleep(1); ?>
<script>countit(3)</script>
</body>
I have a php script which process several records from a database and I want to display a counter
of the current recod being processed. I thought JS was the way to do that. I saw something very similiar to the code above recommended on so.
Any insight would be greatly appreciated.

PHP buffers the output and doesn't send the page until it has finished running. The sleeps do not run between execution of script elements.
Rewrite your logic to use a JavaScript setInterval instead.
Alternatively, disable or avoid output buffering in your PHP script, but note that this is likely to have implications on the ability of browsers to cache your page.

PHP is a server side language, while Javascript is client side. I'm guessing you are simply seeing 3 in you counter div. The reason is because the PHP sleep(1) is happening before the page is even rendered. You need use a setInterval in Javascript to accomplish what you are trying to do.

The problem is your php code executes on your server, while you need code to execute on the client (JavaScript) for this to work:
<script>
var idx = 1;
var doCount= function(){
if(idx >= 3) return;
countit(idx);
setTimeout(doCount,1000);
};
doCount();
</script>
remove the following:
<?php sleep(1); ?>
<script>countit(2)</script>
<?php sleep(1); ?>
<script>countit(3)</script>

Your code waits 2 seconds and the browser receives:
<head>
<script>
function countit(i)
{
document.getElementById('counter').innerHTML = i;
}
</script>
</head>
<body>
<div id="counter"></div>
<script>countit(1)</script>
<script>countit(2)</script>
<script>countit(3)</script>
</body>
that's probably not what you want.
let's try something like this:
<script>
var i = 1;
function counter()
{
if (i < 4)
{
countit(i);
i++;
window.setTimeout(counter,1000);
}
}
counter();
</script>

Related

Read Cookie Data from PHP in Javascript

I have a PHP file that contains both the PHP Code and the JQuery Code. My motive is to set cookies as and when the PHP code is executing and read the cookies set by PHP in the JQuery part of the code and make some decision. But I'm not able to do that. What would be the best way for me to achieve this.
I'm new to PHP any help would be great.
<?php>
if(isset($_POST['StartProcess'])){
$Process_step = 1;
setcookie("MyCookie", $Process_step); sleep(30);
$Process_step = 2;
setcookie("MyCookie", $Process_step); sleep(30);}
<?>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
var abc = document.cookie.split(";").map(function(el){ return el.split("="); }).reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
console.log(abc["MyCookie"]);
if(Step == 1){ do something;}else if(Step == 1){ do something else;}
})
})</script>
<head>
<body></body>
</html>
If I understand your question correctly, you would like to use PHP session value on the JQuery.
You can print the variable of PHP in the JQuery line. You can do it like this
var myvalue = "<?PHP $phpvarname ?>"
or you can use PHP session and assign it on the var.

executing jquery code from php

$("#bt-potrdi").click( function(e) {
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
when i click on button this jquery code is executed and works fine. Can i execute this code without click event?
I want to execute this code from php when some data is executed successfully like for example
if ($ok) {
?>
//execude ajax code
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
<?php
}
is this possible? PHP is server side code so i didn't find any good example if this is possible
Similar to the other suggestions, but this doesn't rely on having 2 copies of the same code...
if ($ok) {
?>
<script type="text/javascript">
$(function() {
$("#bt-potrdi").trigger("click");
});
</script>
<?php
If you ever change the click event handler, this will still work. This means that you won't need to make any future changes in 2 places.
If I understand the question, you want to execute some javascript on page load if $ok is true. To do that, you should be able to do something like:
if ($ok) {
?>
<script type="text/javascript">
//execute ajax code
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
EDIT: Also, e.stopPropagation(); is not going to work because e is not defined anywhere.
What happens is when your PHP script is executed, if $ok evaluates to true, then your jquery code is included in the generated document, and is omitted if it doesn't. But at this point, there is no event, so the following line will not work.
e.stopPropagation();
However, as jdwire suggested, you can wrap your javascript in a script tag, and have it executed that way, without being triggered by an event. So... like this:
<?php
if ($ok) {
?>
<script type="text/javascript">
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
?>
I would design my code so that i could add classes and set z-indexes straight up when html is rendered, but if you want to do those with jquery, jsut wrap them in <script> and $(document).ready(function({}); so they will be executed when dom is ready.
eg.
if ($ok) {
?>
//execude ajax code
<script>
$(document).ready(function{
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
</Script>
<?php
}
edit
Okay i assumed e.stopPropagation(); is set somewhere before since it was in questions example aswell. removed it for now.
You can echo out the code in <script/> tags and it will be run as JavaScript, or with the code you have, just place it between tags and it should be fine :)
But you cannot do this "live". Only when the page is requested ONCE.
You can also do it this way to pass PHP variables over to javaScript. I think it's a lot cleaner.
$check = 1;
?>
...
<script type="text/javascript">
var check = <?= $check; ?>;
...
if (check)
{
$("#bt-potrdi").trigger("click");
}

How to execute PHP code within JavaScript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>

Javascript countdown timer that stops when window is not in focus

Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance
You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this
In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.

PHP and jQuery function—only works once?

I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn't refresh?
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
$('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');
});
});
</script>
It's because you're using PHP to generate the random number, and it can't possibly be refreshed across calls to the JS function -- it's embedded in the HTML by that point.
May be you can also use live like instead of click
$(document).ready(function(){
$('#btn-get-random-image').live("click", function () {
// your works here
}
});
also check out jquery live
As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!
Edit: modified code to make it suck less.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var myPics = <?php echo json_encode($pics); ?>;
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
var index;
do {
index = Math.floor(Math.random() * myPics.length);
} while ( typeof myPics[index] == 'undefined' );
$('#my-img')
.attr('src', myPics[index]);
});
});
</script>
This uses PHP's JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The do/while loop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.
Your PHP is creating JS code, which gets sent to the browser once when the page is rendered. Each call to the JS function runs the function as it existed when the page was rendered.

Categories