Enable PHP page with jquery

Asked

Viewed 184 times

0

We took a system from which all pages are in HTML. Only that the customer wishes that each person who accesses his site, the information as IP, date and time were stored in a database. About the storage all right, but how could I do so when accessing the site, jquery activated the page in PHP that makes this registration? If we had to replace index.html with index.php, it would be more work, because its site has several pages and we would have to change the link in all.

  • Ajax solves, doesn’t it? You could inject an Ajax that would require a single PHP that would do this.

  • Hello William, resolve yes. Could you give me an example? because I don’t know much Ajax.

  • Fox, see if you can understand the answer

2 answers

1

According to this site this function in jquery executes some command when loading a page

// A $( document ).ready() block.
$( document ).ready(function() {
   console.log( "ready!" );
});

And second this other site this function sends a POST:

$.ajax({
   type: "POST",
   url: url,
   data: data,
   success: success,
   dataType: dataType
});

Combining the above two ideas in a very simplified way:

$( document ).ready(function() {
   // manda a requisição para o PHP aqui.   
   $.post( "paginaQueSalvaDadosNoBanco.php", { ip: "192.168.1.1", hora: "02:00" } );
});

Okay, putting this in your index.html solves the problem :D

0

Create a file called log.js or anything like that and put it in the "root" of the publish folder (public_html or www, depends on your system)

Then create a file called log.php also at the root

Now on the log.js add this:

note: (new Date().getTime()) is only to avoid caching

(function (d) {

    function trigger() {
        var oReq = new XMLHttpRequest();

        //Defina como true
        oReq.open("GET", "/log.php?_=" + (new Date().getTime()), true);

        //Envia a requisição, mas a resposta fica sendo aguardada em Background
        oReq.send(null);
    }

    //Verifica se a página já foi carregada
    if (/^(interactive|complete)$/i.test(d.readyState)) {
        trigger();
    } else {
        d.addEventListener('DOMContentLoaded', trigger);
    }

})(document);

In the log.php add to your mysql instructions:

<?php

//Conecta
$mysqli = new mysqli("localhost", "usuario", "senha", "banco");

if (mysqli_connect_errno()) {
    printf("Erro de conexão: %s\n", mysqli_connect_error());
    exit;
}

$ip = $_SERVER['REMOTE_ADDR'];

$result = $mysqli->query('INSERT INTO `logs` (`data`, `ip`) VALUES (now(), \'' . $ip . '\')');

if ($result) {
    $result->close();
}

$mysqli->close();

Now on all HTML pages add

<script src="/log.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.