Jump to content

Echoing php in js


RynMan

Recommended Posts

Hey guys

 

I've got a menu built using a third party tool and it has effectively created all of the javascript which is nice.  What I'm trying to do is have the sub menu text and links pulled from mySQL using PHP.  I've got the php to do this and it work great.  However, I now essentially want to just echo the text that the php pulls from the database, in the .js file.  How can I do this?  Is it an option to bring all of this javascript into the php document where I'm displaying the menus somehow, then run the query in there and effectively add the echo?

 

Thanks guys for any help/suggestions.

Link to comment
https://forums.phpfreaks.com/topic/197092-echoing-php-in-js/
Share on other sites

PHP is processed (server-side) long before Javascript is processed (client-side). You can use PHP to output Javascript however if that is what your asking.

 

Can't really help much without seeing some code.

 

Thanks Thorpe. 

 

I'm trying to basically echo this in my PHP document, amongst some other javascript.

 

echo 'it=s2.addItem(5,6,7,"'John Smith'",n,n,"","",n,n,n,n,n,112,20,2,0,0);';

 

However it is killing my javascript on the page.  Nothing appears.

Though, when I do this....

 

it=s2.addItem(5,6,7,"<?php echo "John Smith"; ?>",n,n,"","",n,n,n,n,n,112,20,2,0,0);\n';

 

it works fine. :(

Link to comment
https://forums.phpfreaks.com/topic/197092-echoing-php-in-js/#findComment-1034633
Share on other sites

Alright..this is a two part answer.

 

#1)  Yes, you CAN echo php into JavaScript IF (this is important) it is in a file that is parses by php on your server (in most instances a .php or sometimes a .HTML file depending on your config.  What this means is inside "inline JavaScript"  you can echo php into it.  But, this brings me to part 2

 

#2)  It is...without a doubt, best practice to segment your JavaScript away from your php.  If you need to retrieve server side data for your JavaScript, it is almost always best to do it via an ajax request.  This let's you still keep ALL of your JavaScript in .js files by themselves (where it belongs!).  With php5 giving you json_encode this is painfully easy.

 

So in short...you can get away with option #1 (inline JavaScript) but the right way is via making a server side request.

 

Let me know if you have any problems!

Link to comment
https://forums.phpfreaks.com/topic/197092-echoing-php-in-js/#findComment-1035017
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.