I'm looking for some guidance on how if I have an already existing php variable, that is not a web element, just a string, how can I pass that as a variable to ajax?
here is a santized snippet of what I'm doing.
I want to be able to pass $my_php_var to ajax.
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
var my_php_var = $my_php_var;
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:my_php_var},
dataType:"text",
success:function(data);
{
alert(data);
}
})
CodePudding user response:
What you can do is, print it there inside another PHP
tag:
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
var my_php_var = $my_php_var;
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:<?=$my_php_var?>},
dataType:"text",
success:function(data);
{
alert(data);
}
})
Where <?=$var?>
is short version of <?php echo $var; ?>
.