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>
Related
I need to retrieve session variable data inside an ajax call. Here is my try.
$('#update').click(function(){
var number = $('#num').val();
var curuser = <?php echo $_SESSION['userName'];?>
if( number != '' && number.length==9 )
{
$.ajax({
data:{number:number},
success:function(data){
$('#number_add').val(number);
$('#new_data_Modal').modal('show');
}
});
}
});
Seems like var curuser = <?php echo $_SESSION['userName'];?> prevents opening my model(new_data_Modal) after button(update) click. When I remove that line it works fine(Model is opening as previous).
But alert("<?php echo $_SESSION['userName'];?>") is working and it prints the session variable as well.
Can someone show me where I made the wrong?
If this is a string you need to wrap the variable in quotes:
var curuser = '<?php echo $_SESSION['userName'];?>';
otherwise, when PHP code is executed you will get a syntax error:
var curuser = John
You can check the source code of the generate HTML to see what is the output.
NOTE: Your javascript code needs to be a PHP file with a PHP extension, it can be your HTML or JavaScript file. You can use JS file as PHP script in script tag <script src="code.php"></script>
If you're outputting JavaScript values from your php script you should use json_encode, that way any data type will work and there is no risk of your code breaking if you data has a quote or new line in it.
var curuser = <?php echo json_encode($_SESSION['userName']);?>
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 trying to build some javascript function and I need to check if the users are logged in or not. When a user log in to my site I set a variable in session array named is_logged. I want to reach that variable in javascript is it possible???
I tried some ways but did not work like following:
var session = "<?php print_r $_SESSION['is_logged']; ?>";
alert(session);
and:
var session = '<?php echo json_encode($_SESSION['is_logged']) ?>';
alert(session);
It is either show a text or never alert at all
Just echo it:
var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>;
alert(session);
You need tertiary operator, as false is echoed as empty string so it would lead to var session = ; which is a JS syntax error.
If you want to reach all elements of $_SESSION in JavaScript you may use json_encode,
<?php
session_start();
$_SESSION["x"]="y";
?>
<script>
var session = eval('(<?php echo json_encode($_SESSION)?>)');
console.log(session);
//you may access session variable "x" as follows
alert(session.x);
</script>
But note that, exporting all $_SESSION variable to client is not safe at all.
Try the following code:
var session = "<?php echo $_SESSION['is_logged'] ?>";
In a js file you cant get the value of a php variable or php code doesnt works on a js file because php code will works in a .php extension file.
So one method is to set the session value as a hidden element value and in your js file get the value of the hidden element.
In the html:
<input type="hidden" id="sess_var" value="<?php echo $_SESSION['is_logged']; ?>"/>
In your js:
var session = document.getElementById('sess_var').value;
alert(session);
You can do things like this
Just insert the $_SESSION['is_logged'] in a hidden field like
<input type = "hidden" value = "<?php echo $_SESSION['is_logged']; ?>" id = "is_logged" />
Then you can access that in your jquery like this
var is_logged = jQuery.trim($('#is_logged').val());
//then do validation here
var get_session=<?php echo $_SESSION['is_login']
alert(get_session);
?>
## *Just try this * ##
I am trying to pass a PHP variable to Javascript variable for example:
<?php $myvar=10; ?>
<script type="text/javascript">
jsvar = <?php echo $myvar; ?>;
document.write(jsvar);
</script>
How could this be done separating the variable on another page? For instance Page1.html would have the document.write and the variable would be pulled from page2.php
Only with Ajax. For example with jQuery:
$.get('page2.php', function(data) {
alert( data );
});
...
UPDATE
Or alternatively (because smart people pointed out that there is always more than 1 way to go) you can include page2.php in your page1.php and the variable value will become available:
<?php
require_once('page2.php');
?>
<script type="text/javascript">
jsvar = <?php echo $myvar; ?>;
document.write(jsvar);
</script>
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)