开发者

Call jQuery function from PHP

开发者 https://www.devze.com 2023-03-21 00:52 出处:网络
How do I call a jQuery function from PHP? <?php if ($error == 1) { ?> <script type=\"text/javascript\">

How do I call a jQuery function from PHP?

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

开发者_运维问答It doesn´t work.


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


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....


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>
<?
}
?>


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

jQuery.error('1');
// or, uning the $ alias:
$.error('1');


<?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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号