Paulo Soares
Paulo Soares

Reputation: 177

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.

Upvotes: 0

Views: 171

Answers (2)

hungryWolf
hungryWolf

Reputation: 398

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

Upvotes: 1

Dmytro
Dmytro

Reputation: 5213

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.

Upvotes: 1

Related Questions