Refresh the contents of a page without reloading it

Asked

Viewed 14,672 times

2

I am working on a project for college where I would like to update the content of a page without reloading it. The page in question has its content received from a script PHP, which in turn picks up the content in a database MySQL.

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>

Note that the form is filled in by PHP/MySQL. What I would like is that when I click the button, the query to delete was executed and the content of the page was updated without refreshing the page. I even managed to do this at the time of entering a data in the database, but to delete and refresh the page I am hitting myself.

Edit: Complementing the paragraph above, this is how I entered the 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 from a script that is responsible for entering the data into the database:

newNota.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:

addiNota.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 it helps!

  • "I even managed to do this at the time of entering a data in the database, but to delete and refresh the page I am hitting myself." Post your code here.

  • @Andrey, I added in the post. I hope you can understand.

  • Look, man, you can use Ajax to fix this. Here is an example : http://demo.tutorialzine.com/2009/09/simple-ajax-website-jquery/demo.html#page1 How-to: http://tutorialzine.com/2009/09/simple-ajax-website-jquery/

  • I don’t know if this example really helps me, because I don’t want to exchange the content of the page for another, I just want to update it. I think the problem is that the content itself is retrieved by PHP...

  • If you just want to take the values without touching the rest of the content, you can use jQuery.post();

  • @brunodotcom I need to change the content, yes. I need the form be re-created. But the data from it comes from PHP.

  • You can leave a PHP page that will have the function to return this data to you and bring it to you the way you want it, and with the post() function you return the information of this page that you created without having to update the page itself. I use it a lot to make those combobox you select the state and then the city according to the selected state.

Show 2 more comments

2 answers

3


I don’t have much time to create the code today, but I think I should have the skills to do this:

1) add an id to the checkbox:

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

2) Create an onsubmit event as you have already done to record. First save the checkbox array

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

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

4) In php deleteNotas() create a response that has successfully deleted notes:

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 received "OK" take the checbox stored 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’m posting without checking the code, but I think this recipe server for what you want to do.

  • The solution looks perfect! I will test it soon and come back here to say what gave, thank you!

2

Everything is fine until the moment of SUBMIT that when used in a form is managed in a very specific way or is an element from which is expected a "default" action and so happens the "Reload" or as described...

was executed and the content of the page was updated without updating the page.

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

event.preventDefault();

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

in form adds an ID:

<form id="exemplo">

later in javascript:

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

Browser other questions tagged

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