How do I call a jQuery function from PHP?
<?php
if ($error == 1) {
?>
<script type="text/javascript">
error('1');
</script>
<?
}
?>
It doesn ́t work.
-
1What exactly do you want to achieve? (You cannot call jQuery from PHP per se)MeLight– MeLight2011年07月17日 08:48:06 +00:00Commented Jul 17, 2011 at 8: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– khattam2011年07月17日 10:52:25 +00:00Commented Jul 17, 2011 at 10:52
5 Answers 5
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
Comments
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....
1 Comment
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>
<?
}
?>
1 Comment
You need to specify that error('1') is a call to a jQuery function:
jQuery.error('1');
// or, uning the $ alias:
$.error('1');
Comments
<?php
if(this == that) {
//do something in php
} else {
//do something with jquery (i.e. fade something in/out
}
?>