how to convert javascript variable to php variable in the same file - javascript

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>

Related

Can't use php variables defined in another file

I have three php files, one defines a constant, the other has the html markup and includes a php file wigh renders js content. the third is the php file rendering the js content. the code is as shown below.
the first file named "config.php" :
<?php
define('TESTVAR','test variable');
?>
the second file named "main.php" :
<?php
require_once ('config.php');
?>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script type="text/javascript" src="script.php"></script>
</body>
</html>
the third file named "script.php" :
alert(<?php echo TESTVAR ?>);
this is what gets loaded as script.php:
<b>Notice</b>: Use of undefined constant TESTVAR - assumed 'TESTVAR' in <b>C:\xampp\htdocs\trials\testphpinjs\script.php</b> on line <b>2</b><br />
TESTVAR);
it's not that php is not being rendered, if i change the script.php to
alert(<?php echo '\'testing'. 'php' . 'echo\'' ?>);
it works perfectly and the loaded script can be viewed from developer tools as
alert('testingphpecho');
the only problem I have is that I cannot access the variables in pages required or included before
Using <script type="text/javascript" src="script.php"></script>, the browser will issue a new request to load script.php directly. Since PHP is stateless, that request will not be handled in the same context as whatever processing goes on in main.php.
If you want to use the variables/constants defined in config.php within script.php, you will have to load it in there:
<?php require_once('config.php'); ?>
alert("<?php echo TESTVAR; ?>");
Note that I've added quotation marks, since TEST_VAR is a string value in your example.
If your Javascript code relies on more than just config.php and its behavior depends on pre-processing that's done in main.php, it might be better to load it as an inline script instead:
<?php
require_once ('config.php');
?>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script type="text/javascript">
<?php include('script.php'); ?>
</script>
</body>
</html>
This way, PHP is loading the script.php file within the same context as main.php, and all constants and variables defined there will (should) be available for use by the code that's outputting your Javascript.

Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function

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>

Opening url retrieved with PHP inside Javascript

Need to open $link with javascript, that is retrieved from an XML file using PHP. Here's the code:
<?php
$url = "map.xml" ;
$xml = simplexml_load_file($url);
$link = $xml->url[mt_rand(0,count($xml->url)-1)]->loc ; // Get Random Location
?>
<html>
<head>
<title></title>
</head>
<body>
<script>
$(document).ready(function(){
window.open($link, "_blank"); // will open new tab on document ready
});
</script>
</body>
</html>
You cannot access php variables from javascript. With php you can render html and javascript on server. So you need to print your $link variable to the page:
window.open("<?= $link ?>", "_blank");
Note that short echo tag <?= is only guaranteed to be available on php 5.4+, if you are stuck supporting an older version use <?php echo instead

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.

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