Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda