0

I have a .php file and .js file. I want to use the php variable in javascript file but its not working. I found a solution by using session but that didn't worked.Can anybody provide me a solution or have a look at the code if there is any mistake.

In .php

 $wd=500/$w;
 $_SESSION['wd']=$wd;

In .js

  var sf= <?php echo json_encode($_SESSION['wd']);?>; 
2
  • 1
    Try var sf= '<?php echo json_encode($_SESSION['wd']);?>'; Note quotes. Commented Mar 30, 2016 at 3:59
  • I tried adding quotes,but its not receiving any value,it shows blank. Commented Mar 30, 2016 at 4:05

2 Answers 2

3

You can pass session value from php file to js by following method .

php file :-

 $wd=500/$w;
 $_SESSION['wd']=$wd;
 echo '<script>var pf = '.json_encode($_SESSION['wd']).';</script>'; 

Js file :-

 var sf = pf;
Sign up to request clarification or add additional context in comments.

Comments

-1

You can simply pass the value through PHP like

 $wd=500/$w;
 $_SESSION['wd']=$wd;
 echo '<script>var passedData = '.json_encode($_SESSION['wd']).';</script>'; 

And catch the the data in javascript like as

 var sf = passedData;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.