Skip to content Skip to sidebar Skip to footer

How Can I Echo Php Within Jquery?

I'm trying to use one of my PHP functions within one of my jQuery functions. I understand that it won't execute the code, but I need to echo the function call, so the server can pr

Solution 1:

You can't -- php commands run during page loading -- your page has already loaded and rendered. You should know php is server side code. This means when your website is requested, your server generates the output file and fills in all the echo values into your output file. The client gets the page with all the variables echo'd to your page -- no php commands are ever given to a client, they're instructions for your server to compile the webpage back to the client.

Why don't you just store absolute_url("login.php") within a javscript variable during your pageload

var loginUrl = "<?phpecho absolute_url("login.php"); ?>";

and then

.html('<h2>Please <ahref="' + loginUrl + '">Login</a>')....

Edit -- oh wait duh -- you are doing that :P sorry for the tangent then, your js file is linked to your page, it's a stub pointing to the file to be included. This does not register php commands.

Solution 2:

This will not actually do anything as you have noted in your question but try:

$('elem').html('<h2>Please <ahref="<?phpecho absolute_url("login.php"); ?>">login</a> or <ahref="signup.php">register</a> to vote for this post.</h2>(click on this box to close)');

If this is coming from a PHP page then try:

$('elem').html('<h2>Please <ahref="&lt;?php echo absolute_url("login.php"); ?&gt;">login</a> or <ahref="signup.php">register</a> to vote for this post.</h2>(click on this box to close)');

Obviously the PHP interpreter will never see this and the PHP code will never be executed as you have already noted in your question.

Solution 3:

you can't do this in your js file, but you can do this in a <script> tag in HTML file.

.html('<h2>Please <ahref="<?phpecho absolute_url(\"login.php\"); ?>">login</a> 
or <ahref="signup.php">register</a> to vote for this post.
</h2>(click on this box to close)')

Solution 4:

Have you checked the source code of the result page? i would use only one " before and after php tags

Solution 5:

I think the proper way to use php from Javascript is by creating web services (in php) and call them from your Javascript. If you want to go really wild, you can send the php content to the server using a web service, write it as a temp file, then 'require' the file and run it... this is quite an off thing to do unless there is a very unique use case that cannot be done otherwise. PHP, as an extremely dynamic language allow this kind of usage.

Post a Comment for "How Can I Echo Php Within Jquery?"