Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript jQuery inside PHP function

This is a theoretical question. My question is whether a jQuery function or script can be written inside a PHP function. E.g.

<?php function phpfunc(){
$a=10; ?>

<script>var a ='<?php $a ?>'</SCRIPT> <?php } ?>

Is this possible and legal?

like image 354
HackerManiac Avatar asked May 10 '14 19:05

HackerManiac


2 Answers

Yes. It is possible and Legal one too. we generally use the same when we require any server side value to be set on client-side on runtime.

Hope this answers your query.

Thanks Much!

like image 105
Anoop Sharma Avatar answered Oct 13 '22 02:10

Anoop Sharma


When php code is interpreted by the sever writing something like:

<?php 

function foo()
    {

        <script type=text/javascript> ... </script>

    }

?>

As part of the code in <?php ?> is interpreted as php and string inside the function doesnt represent any of php functions

You can echo javascript code (or any content of a HTML document) through your php code like:

<?php 

function foo(){

echo "<script type=text/javascript> alert('it works!)'; </script>";


} ?>

so when you execute the function, you wil add the javascript to the document by echoing it and therefore execute it.

You can also use php variables to echo variables to javascript like:

<?php 

function foo(){

echo "<script type=text/javascript> alert('{$phpVariable}'); </script>";


} ?>

or

<?php 

function foo(){

echo "<script type=text/javascript> var variableFromPHP = {$phpVariable}; </script>";


} ?>
like image 39
Bartłomiej Wach Avatar answered Oct 13 '22 01:10

Bartłomiej Wach