Javascript function triggers on page refresh - javascript

I have a hyperlink and clicking on that link will run a JavaScript function. I also have a PHP variable $counter. Inside the JavaScript function, the value of $counter is increased by 1 i.e., $counter++. It works fine. But the same function also runs whenever the page is refreshed. So the value of the $counter is increased by 1 whenever the page is refreshed. I tried all the solutions available on the net like preventDefault(), clickevent handler etc., But nothing works. Please help to fix this. In the below code, I have set $counter as 0. But it loads with 1 as output. I want it to count only when the hyperlink is clicked. Here is my sample code.
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
function onclick() {
<?php
$counter++;
?>
}
</script>
</head>
<body>
link text
</body>
<?php
//tracing counter value
echo $counter;
?>
</html>

TL;DR:
You can't mix PHP and JS code expecting that JS function will execute PHP code.
First PHP prepares output to browser, then Browser parses your JS and HTML. JS never knows about PHP code.
Click CTRL+U to view source as browser sees it - there is no PHP code.
JS function is not run on page refresh. PHP code is run on page refresh.
First goes PHP parser:
session_start();
require("dbconfig.php");
$counter=0;
$counter++;
echo $counter;
Then goes JS/Html parser.
At this point your JS code looks like this:
function onclick() {
}
Content of function is empty because you output nothing from PHP side.
To fix it move PHP var to JS var:
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
var jsCounter = <?= $counter; ?>
function onclick() {
jsCounter++;
console.log(jsCounter);
}
</script>
</head>
<body>
link text
</body>
</html>
Note never output after closing body tag.

Related

How to do not call a JS function after loading the page

I want to load a JS function only when my php code call this function, but not when you visit the page for the first time. My code looks like this:
<?php
function runMyFunction() {
echo '<script type="text/javascript"> JSfunction(); </script>';
}
?>
<script>
JSfunction();
function JSfunction(){
// Code in my function
}
</script>
The problem is that the function JSfunction() is called as soon as the page (index.html) is loaded. But I only want to execute the function with my PHP code, which is called after clicking a button. I would be glad about an answer.
bind the click event on the button to an ajax call, which calls your php code and returns JSON saying whether to go ahead or not.
The other method for this is to have this type of php code:
<?php
if(isset($_GET['myvar'])){
?>
<script type="text/javascript">
//call your javascript here
</script
<?php
}
?>
With that in place have clicking the button reload the page with the GET variable myvar appended to the url.
Example: https://example.com?myvar=1

How do I change the source of an iframe from a PHP if statement using javascript

Based on the result of a PHP if statement, I want to change the source attribute of an iframe.
I have the following:
<?PHP
if {...}
else {
echo "<script>";
echo "document.getElementById('video-embed').setAttribute('src', 'https://www.youtube.com/embed/dQw4w9WgXcQ');";
echo "</script>";
}
?>
<!DOCTYPE html>
<body>
<div class="wrapper">
<iframe id="video-embed" src="...some other youtube video"></iframe>
</div>
</body>
</html>
I know that executing valid JavaScript from the if statement is at least feasible, as I've succesfully tested JS alerts. Everything I've seen online has seemed to indicate that the syntax in question for the line "document.getElem..." is valid. Any help would be appreciated.
You have the Javascript before the HTML that creates the element that it's trying to modify, so getElementById() isn't finding the element. Move the PHP code that adds the JS to the end of the HTML, so that the ID will be found. Or put the Javascript in the window's load handler.
<?PHP
if {...}
else {
echo "<script>";
echo "window.addEventListener('load', function() {";
echo "document.getElementById('video-embed').setAttribute('src', 'https://www.youtube.com/embed/dQw4w9WgXcQ');";
echo "});";
echo "</script>";
}
?>

PHP javascript class variable value in php echo

this is simple example i want java script class variable to php echo please fix the following example to php echo value out put
<!DOCTYPE html>
<html>
<body>
<div class="example">The Book</div>
<? echo '<div class="example">The Book</div>'; ?>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
out put of java-script "The book" but php echo is '<div class="example">The Book</div>' Targeted out put of php The book
Javascript is run on the client, PHP is run on the server. If you want PHP to use the values calculated in javscript you first have to send it to the server, either through something like AJAX, or perhaps just a query string if you don't mind loading a new page or loading the same page again but with a query string appended to the URL.

php completes execution first, then javascript runs

According to the main acceptance of the title, how do you explain the following:
...
$temp1=$_POST['expert_id']; ?>
<script type="text/javascript">
var jstemp1 =<?php echo json_encode($temp1); ?>;
</script>
<?php
$temp1=$_POST['answers_id']; ?>
<script type="text/javascript">
var jstemp2 =<?php echo json_encode($temp1); ?>;
</script>
Suppose $_POST['expert_id']=1 and $_POST['answers_id']=2. My thought is that $temp1 will equal to 2 when Javascript code begins to execute since PHP code executes first. Therefore, jstemp1 would equal to 2 and jstemp2 would equal to 2. However, to my big surprise, jstemp1=1 and jstemp2=2. Can you explain that to me?
Strip out all the JavaScript and you should see what's going on server side; you are literally doing:
$temp1=$_POST['expert_id'];
echo json_encode($temp1);
$temp1=$_POST['answers_id'];
echo json_encode($temp1);
So if $_POST['expert_id'] = 1 and $_POST['answers_id'] = 2 ...
$temp1=1;
echo json_encode($temp1);
// outputs 1
$temp1=2;
echo json_encode($temp1);
// outputs 2
So what you'll have client-side is:
<script type="text/javascript">
var jstemp1 =1;
</script>
<script type="text/javascript">
var jstemp2 =2;
</script>
All the server-side code (PHP) executes before the client-side code (JavaScript)
Your PHP code is inline with HTML/Javascript it will be executed first on the server, true, but the evaluation is be done in the sequence you have wrote it.
You assign a value to a variable, then print it out. After that you assign a different value to the same variable, over-writing it, then print it out.
This is perfectly normal.
PHP executes the code in server side before the page is sended to the browser.
The browser receives:
<script type="text/javascript">
var jstemp1 =1;
</script>
<script type="text/javascript">
var jstemp2 =2;
</script>
And when the page is loaded javascript code is executed.

Call php function on click of a button

I am trying to call a php function on click on a button using Javascript. It does not seem to be working fine.
Is there a better way to call php function on click of a button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function executeShellScript(clicked)
{
var x="<?php ex(); ?>";
alert(x);
return false;
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
function ex(){
echo "Trying to run shell script from the web browser";
echo "<br>";
$contents = file_get_contents('/var/www/shellscriptphp/helloworld.sh');
echo shell_exec($contents);
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
echo $result;
}
?>
</body>
</html>
You cannot invoke a php function just like the way you have explained above. Because php script executions happen before the source of the webpage is sent to the client browser from the server.
However you can do it via an ajax call in which you invoke a client side side js function onclick of the button and and that function inturn makes an ajax call to a server side page and returns the result back.
example:
Here is a sample code which you may refer. This page makes a POST ajax request to itself and gets the response back. Let me know incase of errors as i havent run it here.
<?php
/** this code handles the post ajax request**/
if(isset($_POST['getAjax'])) {
/* you can do this below settings via your php ini also. no relation with our stuff */
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
/* setting content type as json */
header('Content-Type: application/json');
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
/* making json string with the result from shell script */
echo json_encode(array("result"=>$result));
/* and we are done and exit */
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
function executeShellScript(clicked)
{
//$_SERVER["REQUEST_URI"] is used to refer to the current page as we have the ajax target as this same page
$.post('<?PHP echo $_SERVER["REQUEST_URI"]; ?>',{"getAjax":true}, function(data) {
alert(data['result']);
return false;
});
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
</body>
</html>

Categories