Reload hidden div and display it UPDATED when inserting data

0

I have the following problem with JQUERY, AJAX. I have my web that is showing or hiding according to what you are going to use. Clicking NEWS shows us all the news in the BD Inside news there is another button called NEW NEWS where it hides the news list, and shows me a form to upload a new news.

So everything OK, complete the news, upload everything PERFECTLY and without errors to the BD. The problem is to want to go back to the NEWS section, the DIV DOES NOT UPDATE. In other words, if I touch F5 and update the browser, I see the new news, but if after completing the form, I try to return, you do not see that new news uploaded.

I was looking at the load function, and many more answers, but none solved the problem. Is it because my div is hidden? I hope you can help me. I leave the code.

            <div class="col-sm-12 mx-auto text-center mb-3">
                <a id="verNoticias" class="btn btn-outline-primary">
                <i class="fa fa-newspaper-o fa-lg"></i> NOTICIAS</a>
                <a id="verGaleria" class="btn btn-outline-primary">
                <i class="fa fa-camera fa-lg"></i> GALERÍA</a>
            </div>
            <!--SECCIONES NOTICIAS -->
            <div id="seccionNoticias" class="col-sm-12 col-md-5 mx-auto text-center mt-3">
                <h2 class="text-center">NOTICIAS</h2>
                <a id="verNuevaNoticia"><span class="badge badge-success"><i class="fa fa-plus fa-lg"></i> AGREGAR NUEVA NOTICIA</span></a>
                <hr>
                <?php foreach ($noticias as $noticia) :?>
                    <div id="noticia<?php echo $noticia['idNoticia']?>" data="<?php echo $noticia['idNoticia']?>">
                        <a href="editarNoticia.php?id=<?php echo $noticia['idNoticia'] ?>"><span class="badge badge-warning mr-2"><i class="fa fa-edit fa-lg"></i> EDITAR</span></a>
                        <a class="borrarNoticia" id="borrarNoticia<?php echo $noticia['idNoticia']?>"><span class="badge badge-danger"><i class="fa fa-trash fa-lg"></i> BORRAR</span></a>
                        <h4><?php echo $noticia['idNoticia'] .' .- '. $noticia['tituloNoticia'] ?> </h4>
                        <hr>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- SECCION NUEVA NOTICIA -->

            <div id="seccionNuevaNoticia" class="col-sm-12 col-md-4 col-lg-6 mx-auto mt-3">
                <h1 class="text-center">Subir noticias a la Web SB.</h1>
                <form id="formSubirNoticia" class="text-center" method="post" enctype="multipart/form-data">
                    <div class="form">
                        <div class="form-group">
                            <input type="file" class="form-control-file mx-auto" id="imagenNoticia" name="imagenNoticia" placeholder="" aria-describedby="fileHelpId">
                            <small id="fileHelpId" class="form-text text-muted text-center">Seleccione la imagen que quiere subir...</small>
                        </div>

                        <div class="col mx-auto mb-3">
                            <input id="tituloNoticia" name="tituloNoticia" type="text" class="form-control" placeholder="Titulo de la noticia">
                        </div>
                        <div class="col mx-auto mb-3">
                            <input id="noticiaCorta" name="noticiaCorta" type="text" class="form-control" placeholder="Descripción corta de la noticia">
                        </div>
                        <div class="col mb-3">
                            <textarea id="noticiaCompleta" name="noticiaCompleta"  rows="20" cols="50" type="text" class="form-control" placeholder="Noticia Completa..."></textarea>
                        </div>
                    </div>
                    <div class="d-inline-block">
                        <button class="subirNoticia btn btn-success">SUBIR NOTICIA</button>
                        <a href="index.php"><button type="button" class="btn btn-warning">VOLVER</button></a>
                    </div>
                </form>
            </div>

And here's the JQUERY part:

    $("#verNoticias").click(function(){
        $('#seccionNuevaNoticia, #seccionNuevaFoto').hide('fast');
        $('#seccionNoticias').fadeToggle(1000);
     });

     $("#verNuevaNoticia").click(function(){
        $('#seccionNoticias, #seccionGaleria').hide('fast');
        $('#seccionNuevaNoticia').fadeToggle(1000);
     });

     $('.subirNoticia').click(function(){
        var formulario = $('#formSubirNoticia').serialize();
        $.ajax({
            type: "POST",
            url: "subirNoticia.php?p=agregar",
            data: new FormData($('#formSubirNoticia')[0]),
            contentType: false,
            processData:false,
            success: function(datos) {
                $('#seccionNuevaNoticia').hide('slow');          
                $('#mensaje').empty();
                $('#mensaje').append("<div class='alert alert-success alert-dismissible fade show' role='alert'><strong>La noticia ha sido subida correctamente.</strong><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button></div>").hide().fadeIn(1500).fadeOut(6000);
            }
        });
        return false;
    }); 

subirNoticias.php

<?php
require 'funciones.php';

$accion = isset($_GET['p'])?$_GET['p']:'';

if ($accion == 'agregar') {
$imagenNoticia = $_FILES['imagenNoticia']['tmp_name'];
$tituloNoticia = $_POST['tituloNoticia'];
$noticiaCorta = $_POST['noticiaCorta'];
$noticiaCompleta = $_POST['noticiaCompleta'];

$check = @getimagesize($imagenNoticia);
if ($check !== false) {
    $carpeta_destino = '../img/noticias/';
    $archivo_subido = $carpeta_destino . $_FILES['imagenNoticia']['name'];
    move_uploaded_file($imagenNoticia, $archivo_subido);

    $statement = $conexion->prepare('INSERT INTO noticias (idNoticia, imagenNoticia, tituloNoticia, fecha, noticiaCorta, noticiaCompleta) VALUES (null, :imagenNoticia, :tituloNoticia, null, :noticiaCorta, :noticiaCompleta)');

    $statement->execute(array(
        ':imagenNoticia' => $_FILES['imagenNoticia']['name'],
        ':tituloNoticia' => $tituloNoticia,
        ':noticiaCorta' => $noticiaCorta,
        ':noticiaCompleta' => $noticiaCompleta
    ));

    echo "La noticia se ha subido correctamente";
} else {
    $error = "El archivo no es una imagen o el archivo es muy pesado";
    echo $error;
}
}

?>

Another thing I've tried is putting:

   $('#seccionNoticias').load('index2.php #seccionNoticias');

But the VACUUM box appears and without listing the news: S

I have uploaded the web so that you can visualize it more clearly, that perhaps here I have not been.

link -Go to news -Up to new news -Up a new image with title, description and long description -The news is uploaded, click on the NEWS icon to see the list. And the last one does not appear ** BUT IF THE BROWSER IS UPDATED MANUALLY, THEN IF YOU LOAD THE NEWS.

    
asked by ZeR0ByTe 13.11.2017 в 19:01
source

2 answers

0

One solution would be to make the "View news" button delete the content of the div that shows the news and upload all the news that is in the database (such as a news feed ...). So when you save a new piece of news, that the above code as you say works, and click on the "View news" button it will load in the div all, including the new one.

    
answered by 14.11.2017 / 17:48
source
0

Good, when requests are made with AJAX the content of the page is not refreshed therefore it has to influence the behavior you want once successfully made the insertion of the news. Then within the success function of the AJAX apart from performing the three actions that are inside you must add this line:

    success: function(datos) {
            $('#seccionNuevaNoticia').hide('slow');          
            $('#mensaje').empty();
            $('#mensaje').append("<div class='alert alert-success alert-dismissible fade show' role='alert'><strong>La noticia ha sido subida correctamente.</strong><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button></div>").hide().fadeIn(1500).fadeOut(6000);

    //Líneas nuevas
    $noticia = datos.noticia;
    $('#seccionNoticias').append('<div id=' + $noticia['idnoticia'] + 'data=' + $noticia['idnoticia'] + '>',
    '<a href="editarNoticia.php?id=' + $noticia['idnoticia'] + '"><span class="badge badge-warning mr-2"><i class="fa fa-edit fa-lg"></i> EDITAR</span></a>',
    '<a class="borrarNoticia" id="borrarNoticia' + $noticia['idnoticia'] + '"><span class="badge badge-danger"><i class="fa fa-trash fa-lg"></i> BORRAR</span></a>',
    '<h4>' + $noticia['idnoticia'] + '-' + $noticia['tituloNoticia'] + '</h4>',
    '<hr>',
    '</div>');
     $('#seccionNoticias').fadeToggle(1000);
        }

This what it does is add the new news that you must return from the server (variable $ news ) and give visibility to the news section again.

Note: The variable $ news is the instance of the news that arrives in the data parameter from the server.

    
answered by 13.11.2017 в 20:16