Skip to content
Advertisement

Im using JS inside PHP and for some reason the JS won’t go to the else if even when the If isn’t true

As the Title suggests, the code below is some JS inside of a PHP file and for some reason the JS won’t go to the else if even when the if isn’t true. At it’s current state, which ever if statement is put first will run correctly but then the second one will never fire. All this system is designed to do is run x queries when staff === true and run y queries when user == true

session.php

JavaScript

Advertisement

Answer

PHP is executed by the server prior to sending the page content to the browser, once it has arrived in the user’s browser any JS you have sent along with the HTML can be executed then.

However you will not be able to go back and run more PHP code depending on the outcome of a Javascript if statement as you are trying. You do have some options though.

Option 1:

Use PHP to compose some JS expressions or functions that will run in the client side by echoing valid JS expressions into the <scirpt> tag. But again running your MySQL queries will have to happen first during the server-side phase.

Option 2:

You could also use an AJAX-style JS call to call upon a secondary PHP scripts that echo your results as JSON or some other consumable format. jQuery has AJAX functions or look into “Axios” or the browser-native “fetch()”.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Option 3:

Forget about Javascript if you can and write the If…Else into the PHP logic.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement