0

How do I call a jQuery function from PHP?

<?php
if ($error == 1) {
?>
    <script type="text/javascript">
        error('1');
    </script>
<?
}
?>

It doesn´t work.

Daniel
  • 11
  • 1
  • 1
  • 1
  • 1
    What exactly do you want to achieve? (You cannot call jQuery from PHP per se) – MeLight Jul 17 '11 at 08:48
  • PHP is executed in the server and the output is sent to the browser, jQuery is Javascript which runs in the browser. You can do something like user834929 answered, however, it is a better idea to call PHP from jQuery using AJAX. – khattam Jul 17 '11 at 10:52

5 Answers5

6

The script tags cannot be injected directly into php tags.... But if you echo it, the script will work.... The following code works :

<?php
if( some condition ){
    echo "<script>alert('Hello World');</script>";
}
?>

In case of using jQuery, you have to wrap the code in:

jQuery(function(){
    //Your Code
});

and then echo it....

Sharlike
  • 1,789
  • 2
  • 19
  • 30
Kun Ban
  • 61
  • 1
  • 1
  • I just forgot to add ' ' into the alert() function... So please don't forget them... Thank You... – Kun Ban Sep 13 '13 at 12:51
6

No you cannot call jQuery functions from PHP. But you can generate html with PHP that will execute jQuery functions at runtime.

  • Javascript is sent to the client and executed there
  • PHP is compiled at the server and then sent to the client

Big difference in that

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
4

It depends on where you place this code fragment within the HTML output.

One of these solutions, I think, should work:

<?php
if ($error == 1) {
?>
<script type="text/javascript">
$(function() {
   error('1');
})
</script>
<?
}
?>

<?php
if ($error == 1) {
?>
<script type="text/javascript">
$(document).ready(
  function() {
    error('1');
  }
)
</script>
<?
}
?>
user834929
  • 113
  • 6
  • Okay, I can see other answerers suggesting that you can't invoke JS from PHP, and things like that. Of course, you can't. But it also doesn't mean that, for example, displaying some jQuery animation if some condition is met on PHP (server) side, is something you should avoid. So I think the question is legitimate. – user834929 Jul 17 '11 at 09:24
0

You need to specify that error('1') is a call to a jQuery function:

jQuery.error('1');
// or, uning the $ alias:
$.error('1');
Gus
  • 7,289
  • 2
  • 26
  • 23
0
<?php

 if(this == that) {
      //do something in php
 } else {
      //do something with jquery (i.e. fade something in/out
 }

?>

OR using jquery $.ajax to call a PHP function

Community
  • 1
  • 1
Cin Sb Sangpi
  • 687
  • 3
  • 7
  • 22