Is there anyway I can use a php variable in the JQuery script?
Example:
PHP variable: $sr2
Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')
How can I make it so the variable is valid in that JQuery part?
Thanks
PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.
<script type="text/javascript">
var my_php_var = <?php echo json_encode($the_php_var) ?>;
</script>
or retrieve the value via an AJAX call, which means you're basically creating a webservice.
What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.
<script type="text/javascript">
<?php
$phpVar = "foo";
echo "var phpVariable = '{$phpVar}';";
?>
</script>
Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -
<script type="text/javascript">
var phpVariable = 'foo';
</script>
Now your phpVariable is available to your JavaScript! So you use it like you would in any other case -
$("div."+phpVariable);
That will retrieve us any <div> element with a foo class -
<div class="foo"></div>
Assuming your jQuery is in the same file:
... $('#a2_bottom_<?php echo $sr2 ?>') ...
You could output it as part of the page in a script tag... i.e.
<script type="text/javascript">
<?php
echo "var sr2 = \"" . $sr2 . "\"";
?>
</script>
Then your jQuery line would be able to access it:
$('#a2_bottom_' + sr2)
Related
Here I want to use session variable's value in javascript function. I tried
var varname = '<?php echo $_SESSION["variable_name"]; ?>';
But it doesn't pass the value it shows the string
so how can i use session variable of php inside the javascript.
Actually I want to check captcha code in java script side.
Here i already make contactus.php file where I generat captcha value from rand function. Then i store this value in session variable. Here I already made validation.js file to validate contact us form fields so in same file i want to validate captha so for that I has been trying below code but its not working .
var cap = document.frm.captcha.value;
var ca = '<?= addslashes($_SESSION["code"]); ?>';
alert (cap); //ITs shows my entered value perfectly
alert (ca); //but it doesn't show generated captcha value. it simply print '<?= addslashes($_SESSION["code"]); ?>'//
if(cap!=ca)
{
alert("Insert correct captcha code");
document.frm.captcha.focus();
return false;
}
I checked session variable value it works fine on php page but dosen;t work on javascript page.
<script type="text/javascript">
<?php echo "var variable = '". $_SESSION['variable']."';" ?>;
</script>
The file which contains this code must be named .php and has to be a session_start(); at the beginning of the PHP-File.
Then this code should work.
There is several posibilities, why your code isn`t working.
There is an error in variable (Eg unescaped quote)
Code is outside of Javascript code.
Session is not started in the moment of getting variable
For fixing this 3 errors you need to use following code -
<?php session_start(); ?>
<script type="text/javascript">
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
</script>
If in your session variable is not a string or number you need to pack it to the JSON object. In this case you can just make following:
<?php session_start(); ?>
<script type="text/javascript">
var varname = <?= json_encode($_SESSION['variable_name']); ?>;
</script>
Last variant of code will make all types of variable are frendly to JS. Also string.
For example with json_encode from asd'd"sa string you will get "asd'd\"sa" string.
UPD:
If you use this file like JS file like follows:
<script type="text/javascript" src=".../path/to/file.php"></script>
for correct work you need to use following code.
<?php
session_start();
header('Content-Type: text/javascript');
?>
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
Try like this:
<script type="text/javascript">
var varname = <?php echo $_SESSION["variable_name"]; ?>;
</script>
I have some pages. In these pages i want to show the error message.
Now i am showing these message through JavaScript.But the code is repeated so many times that's why i have decided to define this message as a constant in config file.
I accessed this constant STORE_OFFLINE_MSG in a div. And then I am using the html of this div , this function return the text of the div as defined in config file and passes it in the variable of JS
this is the code in my config file config.php:
define('STORE_OFFLINE_MSG','hello');
This is the sort of code of php file abc.php
<div class="storeOfflineMsg"><?php echo STORE_OFFLINE_MSG;?></div>
<script type="text/javascript">
var msg = $(".storeOfflineMsg").html();
$.prompt('<h3 Store unavailable</h3>'+msg);
</script>
but if i used this variable in other file only by using the div class then .html() returns NULL.
My second file xyz.php is as:
<script type="text/javascript">
var msg = $(".storeOfflineMsg").html();
$.prompt('Store unavailable</h3>'+msg);
</script>
Please suggest me what to do. and how can i get a php constant in the Java Script through div class.
You can store the variable directly in javascript variable.
<script type="text/javascript">
var msg = "<?php echo STORE_OFFLINE_MSG;?>";
If you want to pass data from PHP to Javascript try this:
echo the data out in the of your page within a script section.
<script type="text/javascript">
<?php
echo 'var offlineMsg = ' . STORE_OFFLINE_MSG . ';';
echo 'var onlineMsg = ' . STORE_OnLINE_MSG . ';';
?>
</script>
These Javascript variables will then be availabe globally to all other javascript code on the page. Much better than placing it in a hidden div.
I am passing a PHP variable to Javascript, but only at a specific point in the code. As the PHP code continues, the variable I need changes. I could easily just run the Javascript and grab the PHP variable when the page is done loading, but that won't pass the information I want. I want the Javascript to grab the PHP variable at that point, and then ignore subsequent changes to it.
The actual program I'm working with is several thousand lines of code, so I created a simple page to mess around with this issue. The code below shows what I'm trying to do.
<?php
$php_var = 'something';
if(true) {
$php_var = 'new';
echo '
<script type="text/javascript">
js_var="<?php echo $php_var; ?>";
alert(js_var);
</script>
';
}
$php_var = 'later changes';
?>
<script type="text/javascript">
var js_var;
</script>
This doesn't work, however. js_var is set when the inline script is run, but it is just set to a string that says <?php echo $php_var; ?> rather than actually evaluating it.
PHP runs first, and whatever JS is sent to the browser is run. I think you just want this:
echo '<script type="text/javascript">
js_var = '.json_encode($php_var).';
alert(js_var);
</script>';
$php_var = "foo";
echo '
<script>
var js_var = '. json_encode($php_var) .';
alert(js_var);
</script>
';
Produces:
<script>
var js_var = "foo";
alert(js_var);
</script>
<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>
how can use JS variable in PHP like this ?
<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>
this doesn't work :(
And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.
You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:
<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
echo 'listArray[', $key, '] = ', $value, ";\n";
}
You can't use it directly like this.
You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.
Using jQuery it can become really simple though:
x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
alert("response from PHP: " + result);
});
And in the PHP read the x from querystring and send proper output.
it is not possible because both are different languages so you cant use javascript varible
in php inside javascript
This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x.
You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.
like this
if you put php in any single or double quotes than it work
<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>
This will convert javascript variable to php variable.
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php