I have a JavaScript function from which I need to call a PHP function written in a separate file. How can I do this?
-
The PHP function returns a value that I want to assign to a JavaScript variable.
-
Answer:
Assuming you can modify the code in both files: Turn the PHP function into a web service which accepts arguments by URL and dumps its output to the HTTP response. Then call the service with an AJAX request and stick the response into your variable. <?php // http://example.com/add.php function add($a, $b) { header('Content-type: text/json'); echo json_encode(array('sum' => $a + $b)); } add($_GET['a'], $_GET['b']); ?> // This is jQuery, but it could be anything $.getJSON('http://example.com/add.php?a=2&b=2', function(response) { doSomethingWith(response.sum); }); Now all your components are decoupled, but they can still access each other with a well-known interface. (You could also call sum() from another language in the same way if you wanted to, and everything supports JSON these days.) If for some reason that approach won't work, you could do the same sort of thing with JSONP: <?php function add() { // ... work omitted echo $_GET['functionToCall'] + "($sum)"; } ?> // Your Javascript function useSum(sumFromServer) { // Do something with it } <!-- In your HTML: --> <script src="http://example.com/add.php?a=2&b=2&functionToCall=useSum"></script> ---- [1] Please keep in mind this demo code is insecure. In production, you'll at least want to filter the input.
Bulat Bochkariov at Quora Visit the source
Related Q & A:
- How can I call Android JavaScript functions in WebView?Best solution by Stack Overflow
- How can I make a dynamic web page in PHP?Best solution by Yahoo! Answers
- How can I pass global variables into a function?Best solution by Stack Overflow
- How can I separate a video into two parts?Best solution by Yahoo! Answers
- I was trying to send a e-mail and it did not send how can i find it again.Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.