tags:

views:

5184

answers:

5

Hello

How to call a JavaScript function from PHP?

<?php

jsfunction();
// or
echo(jsfunction());
// or
Anything else?

?>

Please let me know.

the follow of my program is, from xyz.html (on a button click) it call a wait() in an external xyz.js. This wait() call a wait.php function wait() { xmlhttp=GetXmlHttpObject(); var url="wait.php"; \ xmlhttp.onreadystatechange=statechanged; xmlhttp.open("GET", url, true); xmlhttp.send(null); }

function statechanged() { if(xmlhttp.readyState==4) {document.getElementById("txt").innerHTML=xmlhttp.responseText;}}

and wiat.php loadxml(); "; ?>

where loadxml calls another php the same way. The loadxml() is working fine otherwise, but it is not being called the way i want it. can you please suggest something.

Thank you.

Best Zeeshan

+5  A: 

You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.

Matthew Flaschen
well i am able to call a JS function like this:echo "<td onClick= loadxml()><i>Click for Details</i></td>";.... but i dont want to click anything now. i just want my php to call a JS function with any event.
Zeeshan Rang
That example is using a click event in HTML, not php. JavaScript is client side and php is server side. You cannot directly call JavaScript with PHP.
MrChrister
+6  A: 

I always just use echo "<script> function(); </script>"; or something similar. you're not technically calling the function in PHP, but this as close as your going to get.

GSto
+4  A: 

PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.

Daniel Moura
Strictly speaking, that's not true. There is also server-side JavaScript and you could theoretically have both PHP and JavaScript running on a server and calling each other. In practice, it's or course a very unlikely scenario.
Michael Borgwardt
+2  A: 

Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).

<td onClick= loadxml()><i>Click for Details</i></td>

function loadxml()
{
    result = loadScriptWithAjax("/script.php?event=button_clicked");
    alert(result);
}

// script.php
<?php
    if($_GET['event'] == 'button_clicked')
     echo "\"You clicked a button\"";
?>
Daff
+9  A: 

Look, here's the deal. As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big ol' string. That's it.

All the fancy work you can do with language like PHP - reading from databases and webserivces 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.

Once you grasp that concept, you realize you don't "call javascript from php", you merely "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">'
   , 'jsfunction();'
   , '</script>';

escaping from php mode to direct output mode

<?php
// some php stuff
?>
<script type="text/javascript">
    jsFunction();
</script>

EDIT

You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.

Here's an example of what I think you're doing with jQuery's AJAX

$.get(
    'wait.php'
  , {}
  , function( returnedData )
    {
      document.getElementById("txt").innerHTML = returnedData;
      //  Ok, here's where you can call another function
      someOtherFunctionYouWantToCall();

      // But unless you really need to, you don't have do
      // We're already in the middle of a function execution
      // right here, so you might as well put your code here
    }
  , 'text'
);


function someOtherFunctionYouWantToCall()
{
    // stuff
}

Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.

$.get(
    'wait.php'
  , {}
  , function( returnedData )
    {
      // Assumes returnedData has a javascript function name
      window[returnedData]();
    }
  , 'text'
);
Peter Bailey
There's off course also the option of linking in an external javascript file that does the call itself... That way you keep JavaScript where it belongs, in the JavaScript code. =)
PatrikAkerstrand
this is not working. i tried both of them. the follow of my program is, from .html (on button click) it goes to an external .js function which load a php file (using xmlhttp=GetXmlHttpObject();var url="phpwithmysqlwait.php"; xmlhttp.onreadystatechange=statechanged; xmlhttp.open("GET", url, true); xmlhttp.send(null); )and my php call <?php echo "<script> loadxml(); </script>"; ?>where loadxml calls another php the same way. The loadxml() is working fine otherwise, but it is not being called the way i want it. can you please suggest somthing
Zeeshan Rang
Update your original question with this info so that it's easier to read. I can modify my answer to address these specifics
Peter Bailey
question updated
Zeeshan Rang
Great answer P!
Sam