Reputation: 83
I need to copy the value of a jquery variable into a PHP variable.
My code:
<script>
$(document).ready(function() {
var gtext = "Sample text";
console.log(gtext); //I get the gtext printed in console
<?php $variablephp = "<script>document.write(gtext)</script>" ?>
<?php echo $variablephp; ?> // I cannot get printed this php variable
<?php echo "hi"; ?> //This echo statement not get printed
});
</script>
Can anyone please help on this?
My question is different in the sense I want to store a jquery value inside a PHP variable. Not a PHP variable into a jquery element.
Upvotes: 0
Views: 4350
Reputation: 2926
This would be a jquery to php method
inside index.php
<button id="button1">Press Me</button>
<script type="text/javascript">
$( "#button1" ).click(function() {
$.ajax({
method: "POST",
url: "server.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
});
});
</script>
<?php
//This will display the session data
if(!empty($_SESSION)) {
print '<pre>';
print_r($_SESSION);
print '</pre>';
}
?>
inside server.php
<?php
session_start();
function cleanInput($string)
{
return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
}
if(!empty($_POST['name'])) {
$_SESSION['name'] = cleanInput($_POST['name']);
}
if(!empty($_POST['location'])) {
$_SESSION['location'] = cleanInput($_POST['location']);
}
Then after the user clicks the button, if they refresh the page the php $_SESSION will contain the new data
Upvotes: 1
Reputation: 2926
This would be a php to jquery method
<script type="text/javascript">
$(document).ready(function(){
var example = '<?php echo $phpVariable; ?>';
});
</script>
Upvotes: 2
Reputation: 83
Okay. So Why I wanted to store the jquery value into a PHP variable is, I wanted the values I got in jquery as session variables in PHP.
Because I want these jquery values to be specific for each user.
Is there any other option in jquery itself, to behave this jquery value like a session variable in PHP?
Sorry if this is irrelevant, as I am new to all this.
Upvotes: 1
Reputation: 302
You can use php like this :
<script>
$(document).ready(function (e) {
<?php if (isset($variable) && $variable !=''){ ?>
var abc = 'this';
<?php }else{ ?>
var abc = 'that';
});
</script>
Upvotes: 1