Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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):

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!