• Home
  • Recent Q&A
  • Java
  • Cloud
  • JavaScript
  • Python
  • SQL
  • PHP
  • HTML
  • C++
  • Data Science
  • DBMS
  • Devops
  • Hadoop
  • Machine Learning
in PHP by
How to call a JavaScript function from PHP?

How to call a JavaScript function from PHP?



  // or


  // or

  // Anything else?

The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.

function wait()



  var url="wait.php"; \


  xmlhttp.open("GET", url, true);


function statechanged()


  if(xmlhttp.readyState==4) {




and wait.php

<?php echo "<script> loadxml(); </script>";

where loadxml() calls code from another PHP file the same way.

The loadxml() is working fine otherwise, but it is not being called the way I want it.

1 Answer

0 votes

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.

All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".

There are many ways to do this, but here are a couple.

Using just PHP:

echo '<script type="text/javascript">',




Escaping from php mode to direct output mode:


    // some php stuff


<script type="text/javascript">



Related questions

0 votes
asked Mar 19, 2020 in PHP by DavidAnderson
0 votes
asked Jun 6, 2020 in PHP by SakshiSharma