Skip to content
Advertisement

Why are two functions running on button click instead of just one?

I have 2 buttons in a page. One of the buttons saves a date that is input via 3 textboxes. The other one calls a function that does some data manipulation.

This is what I have from the first button referred above.

<input type="submit" name="gravarnext" value="Gravar" />

<?php
if (isset($_POST['gravarnext'])) { 
    if ($_POST['atextfield1'] <= 0 OR $_POST['atextfield2'] <= 0 OR $_POST['atextfield3'] <= 0 OR $_POST['atextfield1'] > 31 OR $_POST['atextfield2'] > 12 OR $_POST['atextfield3'] < 2013){ ?>
        <script>window.alert("Um ou mais valores são inválidos (Dia 1-31 / Mês 1-12 / Ano 2013+).");</script>
    <?php } else {
                $qp = "UPDATE login.next SET dia = '".$_POST['atextfield1']."'";
                $rqp = mysql_query($qp);
                $qp = "UPDATE login.next SET mes = '".$_POST['atextfield2']."'";
                $rqp = mysql_query($qp);
                $qp = "UPDATE login.next SET ano = '".$_POST['atextfield3']."'";
                $rqp = mysql_query($qp);
                echo $_SERVER['PHP_SELF']; ?>
                <script>window.alert("Data do próximo sorteio atualizada com sucesso!");</script>
    <?php } 
}

And this is the respective code from the second button

<button onclick="myFunction()">Finalizar</button>

<script>
    function myFunction()
    {
        var r=confirm("Depois de carregar 'ok', todas as ações tomadas são irreversíveis. Desejas continuar?");
        if (r==true)
        {
            <?php
            //Refresha o palpite do utilizador para 0 e guarda o palpite antigo como ultpalpite
            $qp5 = "UPDATE login.users SET ultpalpite = palpiteatual";
            $rqp5 = mysql_query($qp5);
            //Gera o número sorteado
            $numsort = rand(1,50);
            $qp2 = "UPDATE login.sorteio SET ultsorteio = '".$numsort."'";
            $rqp2 = mysql_query($qp2);
            $qp3 = "UPDATE login.next SET numsorteado = '".$numsort."'";
            $rqp3 = mysql_query($qp3); 
            //Adiciona +1 ao vezesganhou do(s) vencedor(es)
            $qp4 = "UPDATE login.users SET vezesganhou = vezesganhou + 1 WHERE ultpalpite = '".$numsort."'";
            $rqp4 = mysql_query($qp4);
            //Atualiza data do ultimo sorteio
            $d = date('j');
            $m = date('n');
            $y = date('Y');
            $aqp1 = "UPDATE login.sorteio SET diaultsort = '".$d."', mesultsort = '".$m."', anoultsort = '".$y."'";
            $arqp1 = mysql_query($aqp1);
            ?>
        }
        else
        {
            return 1;
        }
    }
</script> 

So, my problem is that whenever I click the first button (called “Gravar”), everything run perfectly except that the function associated to the second button (called “Finalizar”) runs too. What may be causing this? And don’t worrie with the sql vulnerabilities and/or bad coding. This is just for testing purposes.

Advertisement

Answer

Your button Finalizar always runs for a very simple reason:

You can’t combine PHP code with a JavaScript function. PHP code is run before it is sent to the client (hence it’s called a server-side language).

If you had the following script:

function myJavascriptFunction() {
     <?php echo 'This is some PHP'; ?>
}

The client would interpret it as:

function myJavascriptFunction() {
    This is some PHP
}

which will give you errors. Again, PHP is run server-side.

In order to run PHP from JavaScript, you need something called AJAX. Basically you save whatever you want to do in a separate PHP file. You can run that PHP file silently whenever you like to.

Have a go at this tutorial: http://www.w3schools.com/ajax/default.asp

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement