简体   繁体   中英

JavaScript only works after refresh

I have an issue. I'm working on the following code. In it, there's a calculator function made with JavaScript. I don't get jQuery yet. It works, but it only does so when I refresh the page. The page is a .php file. I don't know if it's got to do with that or the fact that there is php or database queries in the page, or whatsoever really.

The page is organized in the following fashion:

<div> 

<div> 

<?php -> catch $_POST values from another page -> some database query(select->echo selected item->turn item into $var) ?> 

    <div style="background: white; box-shadow: 1px 1px 2px; width: 200px; padding: 10px; float: right; margin-top: -125px; margin-right: -10px; height: 150px;">    

    <input type="radio" name="opcao" id="opCart" >Cartão<br>
    <input type="radio" name="opcao" id="opDin">Dinheiro<br>

    <input type="text" id="cholerie" style="width: 70px;" required> 
    <input type="submit" id="calcular" onclick="calcula()" value="calcular"> Resultado: <p id="resultado"></p>
</div>

    <script>
         var preco = <?php echo $array[preco]; ?> ;
         var pagamento = document.getElementById("cholerie").value;
         var troco = Number(preco) + Number(pagamento);
         function calcula(){
            document.getElementById("resultado").innerHTML = troco;
         }
    </script>

< some form to catch $_POST values from the database query >

<div> </div>
mysqli_close($conn);

I think the issue is the javascript and its related form.

php only runs when you reload the page. if you need to update page without reloading, you need to use ajax to send asynchronous query to a php page and update your data.

I too feel Dmitry's answer is right, how will you get your live data without reloading the page? You can use AJAX though as he suggested, so go ahead and read on AJAX on google

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM