Page 1 of 1

Calling javascript function from php Code!!!

Posted: Sat Apr 17, 2010 4:23 am
by parmita
Hi Every1
I have a piece of coding in which i need to call a java script function from inside of php code. This java script () is used to display a pop up window for showing a error message. Now , the case in php coding inside a textbox's text area i wrote an if - else condition. Inside that else part it should call that java script (). Now whatever i write in else part its coming in text area. How i will do this?? .....Please help someone...its bit urgent as i need to submit a project. :cry:



Parmita

Re: Calling javascript function from php Code!!!

Posted: Sat Apr 17, 2010 12:26 pm
by Cirdan
You can't call Javascript from PHP because PHP is run on the server, and Javascript is run in the web browser. You will have to have Javascript call the popup function. I would look into AJAX

Re: Calling javascript function from php Code!!!

Posted: Tue Apr 20, 2010 4:57 pm
by Reviresco
Is this what you're thinking of?

Code: Select all

<?php
if($something == true) {
	do_something();
}
else {
?>
<script type="javascript">
alert('This is an alert.');
</script>
<?php
}
?>
As for putting it in a text box... I'm having trouble visualizing that.

Re: Calling javascript function from php Code!!!

Posted: Tue Apr 20, 2010 5:05 pm
by califdon
Would you please explain what you are trying to do. We are all assuming different things. Cirdan is absolutely correct, based on what you said, but Reviresco assumed that you just wanted to use PHP to send the Javascript to the browser. If you expect your IF condition to be dependent on something that the USER does, then the conditional MUST be in the Javascript code, which will be running in the browser when the condition is tested, but if the conditional is dependent on something that is known BEFORE the page has been sent to the browser, then it could be done in PHP.

Re: Calling javascript function from php Code!!!

Posted: Wed Apr 21, 2010 2:52 am
by JAY6390
As it's been said, use ajax to set the error message, or have a static variable called something like errmsg and then echo out the message as the output in the js (assuming that you put the js code in your page not linked from another file)

Re: Calling javascript function from php Code!!!

Posted: Mon Apr 26, 2010 11:07 am
by Jonah Bron
...like this:

Code: Select all

<script type="text/javascript">
var mesg = "<?php echo $mesg; ?>";
</script>
If you want to display the popup based on a condition, you could do this:

Code: Select all

<?php
$mesg = 'some message';
if (some condition is true){
?>
<script type="text/javascript">
alert('<?php echo $mesg; ?>');
</script>
<?php
}
?>