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.
Related
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.
An input from a form in my index.php page is sent to my search.php page. This input is turned into the PHP variable $q with $_GET. How do I turn this PHP variable into a Javascript variable that is a string? Then how do I pass this string as an argument in a Javascript function in the body tag when the page loads? The onload function only works if the first parameter is a string. Here is my simplified code:
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(*PHP variable turned into Javascript string*, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Javascript within your script tag 'should' be ignored if there's a src for it. However you can't have precompiled php in a js file. One option is to set the javascript variables within your php files, then separately include your js files. If your js files make use of those variables, make sure to set the variables first:
<script type="text/javascript">
var q = "<?php echo $q;?>";
</script>
<script src="assets/js/script.js"></script>
The script doesn't work because you're trying to include an external JavaScript file, while also using the same tag for inline script.
This part
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
Should look something like this
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
Fully fixed code
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(q, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Edit: Footnote
As #dossy points out, you should avoid directly passing user input into the HTML code. Use json_encode() to avoid any malicious code or invalid input.
<script>
var q = <?php echo json_encode($q); ?>;
</script>
This is what json_encode() is for. Other answers that use the naive approach of var x = "<?php echo $var; ?>"; will break if $var contains a double quote, for example.
This is the safest way of doing this:
<script type="text/javascript">
var q = <?php echo json_encode($q); ?>;
</script>
I have file named test6.php having javascript variable i need to convert this variable to php variable but when i run it give me an e error (PHP Notice: Undefined index: variable in /Applications/MAMP/htdocs/test6.php on line 14)
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var variableToSend = 'foo';
$.post('test6.php', {variable: variableToSend});
</script>
</head>
<body>
<?php
$x = $_POST['variable'];
echo $x;
?>
</body>
</html>
note that i have only one file (test6.php) containing javascript code and php code and i am trying to convert javascript variable to php variable in the same file and i need to use post not get or submit form
Why error
you should know the processing of a php file rendering from the server to the client , it is :
1. client request the page
2. PHP parser (in server) -> php 2 HTML -> send to client
2. web browser load HTML
3. JavaScript running ~
so you can't get variable of "variable" when you run your php file . Becuase Js has not been running ~ . you should print the value of php echo at JS after ajax .
how about change the JQuery code
$.post('test6.php', {variable: variableToSend});
to
$.post('test6.php', {variable: variableToSend} ,
function(returnValue){
console.log(returnValue) ;
});
I think it will be ok , but i am sorry i can't test it ~
Check to see if it is set before you output it
<?php
if( isset($_POST['variable']) ) {
$x = $_POST['variable'];
echo $x;
}
?>
But I do not think this is what you actually want. The Ajax call is not going to update the current view.
Bring the php section to the top and use isset($_POST['variable']) to check if the variable exist or not.
<?php
if( isset($_POST['variable']) ){
$x = $_POST['variable'];
echo $x;
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var variableToSend = 'foo';
$.post('test6.php', {variable: variableToSend});
</script>
</head>
<body>
</body>
</html>
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.
I know there are a lot of questions covering something similar, but I've tried the answers without any luck.
Snippet of PHP:
$usernum_query = "SELECT numPersonID FROM tbllogins WHERE txtUserName='$currentuser'";
if(!$usernumber = $db1->query($usernum_query)){
die('There was an error running the usernumber query [' . $db1->error . ']');
}
while($row = $usernumber -> fetch_assoc()) {
$userIDnum = $row['numPersonID'];
$userIDnum = utf8_encode($userIDnum);
}
Snippet of Javascript:
$(function(){
$("#0").click(function(){
var userIDnum = <?php echo json_encode($userIDnum); ?>;
alert(userIDnum);
The most common answer I've come across says to UTF_encode my variable, which I think I've done correctly. I've also tried:
var userIDnum = <?php echo $userIDnum; ?>;
Which doesn't work.
In my HTML outside of the script,
<?php echo json_encode($userIDnum); ?>
return "90" (with the quotes)
<?php echo $userIDnum; ?>
returns 90 (without the quotes).
Within the script, I get null and no alert box, respectively.
Any ideas as to why the variable isn't passed into the script? Thanks!
edit: tried with quotes and got the same result
[Taken from comments as requested]
If I can make a recommendation, put your value in a data-attribute in the HTML (e.g. <body data-user-id="<?php echo $userId ?>">. This keeps you from mixing code languages together which is hard to read, and would allow your external script to run correctly without making it a PHP page.
As far as IE9, I'll take a quick look. You might want to see how jQuery manages the data attributes. You should, at the least, have access to
domObject.getAttribute('data-user-id').
Yep, just did a quick lookup, and even IE10 doesn't support the dataset feature. So, you'll need to use getAttribute for IE <= 10.
A solution based on a suggestion by calamari:
In the HTML:
<!DOCTYPE html>
<!--[if lt IE 11 ]> <html class="ie10orless"> <![endif]-->
<head>
... more code here ...
And in the script:
var oldIE;
if ($('html').is('.ie10orless')) {
oldIE = true;
}
if (oldIE) {
var x = document.getElementsByTagName("div")[0].getAttribute("data-number");
alert("in IE");
alert(x);
} else {
var userinfo = document.querySelector('#user');
alert("NOT in IE");
alert(userinfo.dataset.number);
}
Hope this helps someone else. Thanks everyone for the other suggestions as well.
There are couple of things to check. Lets say this is your script:
<?php $htmlString= 'testing'; //Lets say this is a snippet of your php
?>
<html>
<body>
<script type="text/javascript"><!-- And this is the snippet of your JS -->
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>"; //Make sure there's double
//quotes around your php
alert(htmlString);
</script>
</body>
</html>
Make sure you have PHP and JS in a file called .php. If its an external .js file, php inside it will not work (you can rename the JS file to a .php extension if you have it set up that way)
Also make sure you have the html, php and js setup the way above. There has to be double quotes around php, for example:
var userIDnum = <?php echo json_encode($userIDnum); ?>;
change this to below:
var userIDnum = "<?php echo json_encode($userIDnum); ?>";