1

I have the php page with javascript code inside it. If I have php variable retrieved by back-end server, can it be passed in javascript code? For instance, if I want to check the flag(php variable) inside the javascript code, do I need to hardcode it inside the javascript? Below are the "checkServiceCategory"? (Should it be Dynamic or static)

<?php
foreach ($result as $id=>$value) {
if($value[0]->isServiceCategory)
return true;
}

OR

isEmptyUploadFile(function(r)
{
var checkServiceCategory=document.getElementById('category-group').value;
if(checkServiceCategory!=85 && (fileList == null || fileList.length == 0))
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
location.href = "#uploadImgError";
return false;
}
else 
Ryan Fung
  • 2,069
  • 9
  • 38
  • 60

3 Answers3

2

You can write PHP data into JavaScript before that JavaScript is loaded. So, for example:

<script>
var count = 0;
<?php
echo 'count = 5;';
?>
console.log(count); // Will give 5
</script>

You can do this because the PHP is run on the page before it is ever sent to the client. However, once the code is sent to the client, JavaScript and PHP cannot talk to each other. What you can do at that point is make AJAX requests via JavaScript from your client back to your server, and use PHP to respond to the AJAX request.

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
2

Yes you can use php variables inside the javascript code and php variable is dynamic as

<?php $your_variable = "some value"; ?>

<script>
    var js_variable = '<?php echo $your_variable; ?>';
    alert(js_variable);
</script>
ajshort
  • 3,684
  • 5
  • 29
  • 43
DevOps
  • 438
  • 6
  • 21
1

You can pass value from php to js like this.

var js_var = '<?php echo $some_php_variable; ?>';
Abdul Mannan
  • 1,072
  • 12
  • 19