简体   繁体   中英

Is it possible to store a JavaScript function that returns a string in a php variable?

something like :

<?php
   $phpVar = "<script> function jsFunc(){ return 'Hello world';} </script>";
?>

is that even possible? if no, is there a way to do same thing?

If Ajax is the only solution, how do I retrieve a value of an input and store it as a php variable?

I tried something like this and it doesn't work.

<input type=text value="hello" id="myInput">
<?php    
    $phpVar = "<script> 
        function jsFunc(){ 
            var inputVal = $('#myInput').val();
            return inputVal;
        } 
        </script>";
?>

you can store this string in variable. for php interpreter it will be just a text string, nothing else. but when browser receives this data, string will be recognized as js function.


UPDATE

in this case easiest way for send data from browser to server is use a form. there is many examples in the web how to do it.

PHP runs at server side and JS in the browser (apart node and related technologies). Only way you can do something similar would be do to render from PHP in your HTML a tag <script> </script> and add you JS function and executing it there.

Al thought I would definitely not suggest it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM