I am using PHP conditions and want to know if I can run a JavaScript function without some one have to click on it using JavaScript:
if[$value == 1]
{
JavaScript to run the function
}
How would I do that?
BenMorel
32.7k48 gold badges170 silver badges302 bronze badges
asked Jun 16, 2010 at 21:26
Asim ZaidiAsim Zaidi
25.8k48 gold badges129 silver badges219 bronze badges
First of all keep in mind that your PHP code is evaluated on the server, while JavaScript runs in the browser on the client-side. These evaluations happen in different places, at different times. Therefore you cannot call a JavaScript function from PHP.
However with PHP you can render HTML and JavaScript code such that it is only rendered when your PHP condition is true. Maybe you may want to try something like this:
if[$value == 1] {
echo "";
echo "alert['This is an alert from JavaScript!'];";
echo "";
}
Tidal5
1101 silver badge12 bronze badges
answered Jun 16, 2010 at 21:30
Daniel VassalloDaniel Vassallo
330k71 gold badges497 silver badges439 bronze badges
Javascript is client-side code, PHP is server-side, so you cannot execute javascript while building the page in PHP.
To execute javascript on the client-side as soon as the page has loaded, one way is to use the body onload
handler to call your function:
Better yet, if you can afford the bandwidth, use jQuery and use $[document].ready[]
:
answered Jun 16, 2010 at 21:41
I've found that you cannot do something like this in IE and other browsers. It does work in Firefox though. You have to echo out each line as posted in the other method.
Some javascript code
answered Aug 23, 2012 at 15:11
HaruHaru
1,3692 gold badges14 silver badges39 bronze badges
1
I know this thread is old but I just came across it and wanted to add my technique.
You can also echo the php variable into JavaScript and do something based on its value. I use it to place database values into js so the user can do math on the page with them
var jsvar =
if [jsvar = x]{ do something...}
answered Apr 14, 2017 at 14:23
After some tinkering, I was able to get the following to work within a .php file. This doesn't work in a .html file though.
var login = "";
console.log[login];
if [login == 'f']{ .. do something..}
answered Jun 18, 2019 at 5:48