Error calling a php function from the onclick event

Question:

The following happens to me:

I call a php function from the onclick event, my problem is that the php function executes whenever the page loads, that is, it ignores the onclick .

<a href="archivo.pdf" onclick="funcion()"/a>
  • Probe by calling the function that is on a php page.
  • Probe by calling the page php.
  • Probe calling a javascript function and in this function is the php function call.

In all cases the same thing happens to me, the php function is executed whenever the page is loaded ignores the onclick.

$visitas1 = array();
$visitas1 = contVisitas1();

function contVisitas1(){ 

    $archivo = "contador1.txt"; 
    $info = array(); 

    if (file_exists($archivo)){ 
        $fp = fopen($archivo,"r"); 
        $contador = fgets($fp, 26); 
        $info = explode(" ",$contador); 
        fclose($fp); 

        $mes_actual = date("m"); 
        $mes_ultimo = $info[0]; 
        $visitas_mes = $info[1]; 
        $visitas_totales = $info[2]; 
    }else{ 
        $mes_actual = date("m"); 
        $mes_ultimo = "0"; 
        $visitas_mes = 0; 
        $visitas_totales = 0; 
    } 

    if ($mes_actual==$mes_ultimo){ 
        $visitas_mes++; 
    }else{ 
        $visitas_mes=1; 
    } 
    $visitas_totales++; 

    $info[0] = $mes_actual; 
    $info[1] = $visitas_mes; 
    $info[2] = $visitas_totales; 

    $info_nueva = implode(" ",$info); 
    $fp = fopen($archivo,"w+"); 
    fwrite($fp, $info_nueva, 26); 
    fclose($fp); 

    return $info;

}

Answer:

If you want to run code on the server, you have to send a request one way or another. To do it without navigating to another page (or updating the same), AJAX is used. Therefore, we must differentiate between PHP that runs on the server, and JavaScript that runs on the client side (computer, mobile, tablet …).

It is a very broad subject, so I am not going to try to explain it in its entirety, but I will show a small example. In order not to complicate my life, I use jQuery.get() , but it can be done without any library if you want.

HTML

<script>
function ajax() {
    jQuery.get("ajax.php").then(function (respuesta) {
        document.getElementById("resultado").value = respuesta;
    });
}
</script>
<button onclick="ajax()">pulsa</button>
<textarea id="resultado"></textarea>

ajax.php

<?php    
echo '¡Hola, mundo!';

When you press the button, a "GET" request will be sent to the server asynchronously. When done, the response from the server is put into the <textarea> .

Scroll to Top