Refresh the content of a page without reloading it

2

I'm working on a college project where I'd like to refresh the content of a page without reloading it. The page in question has its content received from a PHP script, which in turn takes the content to a MySQL database.

This is my script PHP :

<?php
    include "php/conn.php";

    function lerNotas() {   
        global $conn;
        $query = mysqli_query($conn, "SELECT * FROM notas");                

        if (!$query) {
            die('A consulta falhou:' . mysqli_error($conn));
            } else {
            while($linha = mysqli_fetch_assoc($query)) {                
                echo "<div class=\"nota\">";
                echo "<input type=\"checkbox\" name=\"ids[]\" value=\"" . $linha['id'] . "\"><br>";
                echo "<span class=\"titulo\">". $linha['titulo'] . "</span><br>";
                echo nl2br($linha['conteudo']) . "<br><br>";
                echo "<span class=\"textoPequeno\">Criado em " . $linha['data_criacao'] . "</span><br/>";
                echo "<span class=\"textoPequeno\">Atualizado pela última vez em " . $linha['data_atualizacao'] . "</span>";
                echo "</div>";
            }
        }
    }           

    function apagarNotas() {
        global $conn;
        foreach($_POST['ids'] as $x) {
            $query = mysqli_query($conn, "DELETE FROM notas WHERE id=".$x );
            if (!$query) {
                die('A consulta falhou:' . mysqli_error($conn));
                } else {                
            }
        }
    }

?>

And that's the content of my page:

<html>
    <head>
        <title>Notas</title>
        <link rel="stylesheet" type="text/css" href="css/styles.css">
        <meta charset="utf8">
    </head>
    <body>
        <nav id="menu">
            <ul>
                <li><a href="./nova_nota.php">Adicionar nota</a></li>
                <li><a href="./ler_notas.php">Listar notas</a></li>
                <li><a href="./exclui_notas.php">Excluir notas</a></li>
            </ul>
        </nav>
        <form action="" method="post">
            <?php           
                echo lerNotas();            
            ?>
            <input type="submit" name="apagar" value="Apagar notas selecionadas" class="buttonEnviar">
            <?php
                if(isset($_POST['apagar'])){
                    echo apagarNotas();                 
                }
            ?>
        </form>     
    </body>
</html>

Notice that the form is filled with PHP / MySQL . What I would like is that when I clicked on the button, the query to delete was executed and the content of the page was updated without updating the page. I even managed to do this by inserting a data into the database, but to delete and refresh the page I'm hitting myself.

Edit: Complementing the paragraph above, this is how I did the insertion of data without reloading the page:

<html>
    <head>
        <title>Notas</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="js/novaNota.js"></script>
        <link rel="stylesheet" type="text/css" href="css/styles.css">
        <meta charset="utf8">

    </head>
    <body>
        <nav id="menu">
            <ul>
                <li><a href="./nova_nota.php">Adicionar nota</a></li>
                <li><a href="./ler_notas.php">Listar notas</a></li>
                <li><a href="./exclui_notas.php">Excluir notas</a></li>
            </ul>
        </nav>
        <div class="formulario">
            <form id="form" name="form">
                <input id="titulo" type="text" name="titulo" placeholder="Título" class="inputTexto"><br>
                <textarea id="conteudo" name="conteudo" placeholder="Conteúdo" class="textarea"></textarea><br>
                <input type="submit" value="Salvar nota" class="buttonEnviar" id="submit">
            </form>
        </div>
    </body>
</html> 

This is the page where you have a link to a script that is responsible for inserting the data into the database:

novaNota.js

$(document).ready(function() {
    $("#submit").click(function() {
        var titulo = $("#titulo").val();
        var conteudo = $("#conteudo").val();
        if (titulo == '' || conteudo == '') {
            alert("Nenhum campo pode ser deixado em branco!");
            } else {
            // Returns successful data submission message when the entered information is stored in database.
            $.post("php/adicionarNota.php", {
                titulo1: titulo,
                conteudo1: conteudo
                }, function(data) {
                alert(data);
                $('#form')[0].reset(); // To reset form fields
            });
        }
    });
});

Which, in turn, uses this PHP script:

addNote.php

<?php
    include "conn.php";

    define('NOME_TABELA', 'notas');
    $titulo = $_POST['titulo1'];
    $conteudo = $_POST['conteudo1'];
    $data = date("Y-m-d H:i:s");

    $query = mysqli_query($conn, "INSERT INTO " . NOME_TABELA . " (titulo, conteudo, data_criacao, data_atualizacao) VALUES (\"" . $titulo . "\", \"" . $conteudo . "\",\"" . $data . "\", null)");

    if ($query) {
        echo "Nota criada com sucesso!";
    }
    mysqli_close($conn);
?>

I hope it's clear and that this helps!

    
asked by anonymous 18.09.2014 / 14:16

2 answers

3

I do not have a lot of time today to create the code, but I think I should have the knowledge to do this:

1) add an id in the checkbox:

echo "<input type=\"checkbox\" name=\"ids[]\" value=\"" . $linha['id'] . "\" id='i:$linha['id']'>"

2) create an onsubmit event as you already did for recording. Before you save the checkbox array

var ch = document.getElementsByTagName("checkbox");

3) do an ajax function to send this data to the server (function deleteNotes () in the php file.

4) In the function php deleteNotes (), create a response that erased the notes successfully:

foreach($_POST['ids'] as $x) {
            $query = mysqli_query($conn, "DELETE FROM notas WHERE id=".$x );
            if (!$query) {
                 $control = false;
                } else {
                 $control =true;
            }
        }

if(!control)
die('A consulta falhou:' . mysqli_error($conn));

return '{"result":"ok"}';

5) If you have received "OK", take the checbox saved in var ch and remove the elements that wrap the notes:

for (var b=0; ch.length; b++){
  if(ch.checked){ 
      c=document.getElementByID("i:"+ch).parentNode();
      c.parentNode.remove(c)
 }
}

I am posting without checking the code, but I think this recipe server for what you want to do.

    
18.09.2014 / 15:29
2

Everything is fine up to now which when used in a form is managed in a very specific way or is an element from which a default action is expected "and so it happens" reload "or as you describe yourself ...

  

be executed and page content updated without updating   the page.

However the action that is "taken" is click and not the action of SUBMIT ... to solve my solution is to use:

>
event.preventDefault();

As I mentioned and to "capture" the SUBMIT DO FORM and not the "click" the solution is:

no form adds an ID:

<form id="exemplo">

then in javascript:

$(document).ready(function() {
    $("form#exemplo").submit(function() {
        event.preventDefault();
        [o teu código]
    });
});
    
18.09.2014 / 23:25