If/then with both php and Javascript


Is it possible to combine an if/then statement with javascript and php? With php we can “combine” php and html by just ending php such as:

<?php if ($is_it_true){?>
<strong>HTML STUFF</strong>
<?php ;} ?>

Is there an analogous way to combine javascript and php?

Basically, I have an if/then statement that checks something from the server AND needs to check out something on the page…in other words, something like:

PHP stuff: IF ($user_type !=“instructor”) && Javascript stuff: (getElementByID("nyroModal)) then back to PHP to do some other stuff.

Thank you,


You could do it only if the JavaScript file was being output dynamically by PHP (which it can do) and that execution never returns to the PHP. For example, you could write a certain line of JavaScript conditionally based on a test in the PHP.

However, JavaScript cannot affect the running of PHP code because PHP is executed on the server, while JavaScript is executed by the client. PHP constructs a web page consisting of HTML, CSS and JavaScript, and once it’s done running, sends the output to the client. The JavaScript doesn’t run until it gets to the client, meaning there’s no way for the JavaScript to pass control back to the PHP code in the way that you’ve shown above.

Instead, you could use a part of JavaScript called AJAX, which allows the client to send and receive messages with the server without having to reload the page. This would seem to be what you would want, since you want the JavaScript to be able to call on some PHP code if a certain condition is true.

That makes sense. I’ll look into Ajax. Thank you for your response!