Abel1416 Posted April 18, 2021 Share Posted April 18, 2021 (edited) I am trying to pass a php variable to javascript but it's not working. This is the "sketch" of my code. <?php $url="asset/go/"; ?> <!DOCTYPE html> <html> <head> <title>Page Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <script> var user="mayor"; var url ='<?php echo json_encode($url); ?>'; if(user=="mayor"){ alert(url); } </script> </body> </html> As it is now, it comes with the output below: <?php echo json_encode($url); ?> If I remove the quotation around the php in d jQuery, it throws an error in syntax. Also both codes are located in the same file named test.php Thanks in advance. Edited April 18, 2021 by Abel1416 Quote Link to comment Share on other sites More sharing options...
MadTechie Posted April 18, 2021 Share Posted April 18, 2021 The file with the HTML AND PHP has to be a PHP file type not at HTML, i am assuming you are calling something.html instead of something.PHP Quote Link to comment Share on other sites More sharing options...
Abel1416 Posted April 18, 2021 Author Share Posted April 18, 2021 (edited) It is a php file. test.php Edited April 18, 2021 by Abel1416 Quote Link to comment Share on other sites More sharing options...
MadTechie Posted April 18, 2021 Share Posted April 18, 2021 13 minutes ago, Abel1416 said: It is a php file. test.php My PHP test file <?php $url="asset/go/"; ?> <!DOCTYPE html> <html> <head> <title>Page Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <script> var user="mayor"; var url ='<?php echo json_encode($url); ?>'; if(user=="mayor"){ alert(url); } </script> </body> </html> Here is mu result <-- view-source:http://localhost/test/312485.php --> <!DOCTYPE html> <html> <head> <title>Page Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <script> var user="mayor"; var url ='"asset\/go\/"'; if(user=="mayor"){ alert(url); } </script> </body> </html> So except for the extra quotes it seems fine I can't seem to get the unparsed php code. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.