简体   繁体   中英

PHP function return value to JavaScript

I need to send result from my PHP file to the JavaScript function/file. I found some of answers like: var x='<?php echo $pathinfo; ?>'; var x='<?php echo $pathinfo; ?>'; or this:

myHtmlFile.html:

<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">

function test()
{
   alert(result);
}

</script>

newEmptyPHP.php:

<?php
     $res="it is result";
     echo "var result = ".json_encode($res).";";
?>

My question is whether there is way return value from php function and not from php file. something like this:

<?php

function phpFunction(){
     $res="it is result";
     return $res;
}
?>

I need simple PHP/JavaScript code without something complex. I want keep many function in one php file and not many php files.

<?php 
function phpFunction(){
     $res="it is result";
     return $res;
}
?>

<script>
var result = "<?php echo phpFunction() ?>";
</script>

The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.

You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.

<?php if (a==a) { ?>
<div>
    <script>
    <?php echo 'do something here'; ?>
    </script>
</div>
<?php } ?>

Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.

The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.

You can use $.get()

You can call you php script which contains the function with parameters in you url request.

And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.

Have a good day!

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