Skip to content Skip to sidebar Skip to footer

Can We Use Php Variable In Javascript And Javascript Variable In Php Code?

i m having problem in using php variable in javascript and having problem in using javascript variable in php. $UpdateText='updateReTotal(Tills,'pos_cash','{$till->till_id}');up

Solution 1:

You just have a quoting issue. :

$UpdateText="updateReTotal(Tills,'pos_cash','{$till->till_id}');updateVariance('{$till->till_id}')";

echo'<script type="text/javascript">'
    , "testFunctionForUpdateTotal('".$UpdateText."');"
    , '</script>';

This is a good example of why you should avoid using echo statements to output HTML. PHP is designed to allow you to embed PHP inside of your HTML and you should take advantage of that:

$UpdateText="updateReTotal(Tills,'pos_cash','{$till->till_id}');updateVariance('{$till->till_id}')";
?>
    <script type="text/javascript">
        testFunctionForUpdateTotal('<?= $UpdateText; ?>');
    </script>';

Solution 2:

If you use concatenation you can put the php variable into the javascript code, and you are using concatenation in your echo already.

php can't see the javascript variable as javascript is on the browser and php is on the server

your best bet is just to pass back the javascript variable

Solution 3:

JavaScript is Client-side. PHP is Server-side. They can, somehow, talk, but it ain't always so easy.

To use a PHP variable in Javascript, you have to ways, I'd say. The easy way is:

var phpVar = "<?phpecho$myVar; ?>";

Or, by echoing:

echo"var phpVar = '{$myVar}';";

But, you'll soon realize this will be printed a little like a constant. This can only be done on the page's rendering, so it's a little limited. It really is, like, if $myVar contains 5, to write this directly:

var phpVar = "5";

The results are the same. Another way to use a PHP var in JavaScript is to AJAX-get it. For example, with jQuery:

$.get("/page_that_sends_my_var.php", { }, function(res) {
    var phpVar = res;
});

By having page_that_sends_my_var.php something like this:

<?phpecho$myVar;

But that will be asynchronous. So, you have two different methods for two different purposes. The first one, synchronously, only works when the page is rendering; the second one works whenever you want through an asynchronous call. I'd probably always use the second method; It's more elegant, and AJAX is something nice to do / have: it makes your application more dynamic.

As for using a Javascript variable in PHP, you can do it in 2 ways too. The first one is to use a Form and include the variable in the form's data during the form's submit; the other one (which I prefer) is to use AJAX calls to a PHP script, and send the variable. Like this:

$.post("page_that_uses_my_var.php", { "myVar" : myVar }, function(res) {
    // do something if you like
});

Then, in page_that_uses_my_var.php:

<?php$jsVar = $_POST["myVar"];

Post a Comment for "Can We Use Php Variable In Javascript And Javascript Variable In Php Code?"