Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to change HTML within PHP code?

What is the easiest way to run Javascript code inside PHP, preferably without using external libraries? Specifically, I need the innerHTML of a div to change depending on some calculations performed using the user’s form inputs that were captured earlier with $_POST in a separate form. How can I get the following JS code to run inside the following PHP code? (My most basic attempt was using echo command, but it’s throwing up errors)

HTML:

<div id="output">
                
</div><!--#output -->

PHP (desired JS included):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if (count($valid_locations)<$num_of_locations){
      echo '<script>const output = document.querySelector("#output");</script>;';
      echo '<script>output.innerHTML = "<div class="alert-danger"> Trip unable to be created. Please adjust the budget/number of travelers/duration etc.</div>;";</script>';
}else{
      createTrip($trips);
}

Right now, the IF condition is True and the code does run, but it echos ";" for some reason. I have verified that the condition is met and it runs by adding in a simple echo "this runs";, which did appear upon refresh. I just don’t understand why it’s outputting to the default echo space and the script isnt running to change the innerHTML of the output div. Is this even possible to do with PHP? If so, what’s the best way? (doesn’t need to be secure, won’t be used publicly). I’ve heard of a few things such as ajax but it seems so complicated. Any explanations on stuff like that specific to this scenario would be greatly appreciated.

>Solution :

Following up on the comments, you don’t need JS to achieve what you want. You could just use PHP

<?php
    $output = null;
    if (!empty($_POST)) {
        //...
        //... do stuff
        //... 
       if (count($valid_locations)<$num_of_locations){
            $output = 'Error occured - bla bla bla';
       }
    }
?>
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <?php if (isset($output)) {?>
        <div id="output"><?= $output; ?></div>
        <?php } ?> 
    </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading