How to call a function asynchronously in PHP?

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

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

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.