Problem when modifying data - Update PHP + AJAX + JQUERY

0

Good morning people, again with a problem. I have a news system implemented. When listing the news and click on the EditNoticia button. The news appears with all the fields to edit along with an input "file" that if a news item is edited, together with its image, it replaces the previous image.

The problem I think is in the AJAX, I do not know what I'm doing wrong or how to call the ID of the corresponding news. I already did the DELETE and it works correctly but I do not know why I do not get the edit that is almost similar.

With this I bring the news. (This works correctly). I do not put the previous code, pq is not necessary I suppose.

elseif ($accion == 'editarNoticias'){

$id = $_POST['id'];

//Consulta BD Editar Noticia segun el ID.
$statement2 = $conexion->prepare("SELECT * FROM noticias WHERE idNoticia = $id");
$statement2->execute();
$noticias = $statement2->fetchAll();

//MODIFICAR DESDE ACA
echo "<h1 class='text-center m-5'>Editar noticias SB</h1>
<form id='formEditarNoticia' class='text-center' method='post' enctype='multipart/form-data'>";

foreach ($noticias as $noticia) {
echo "<div class='form-group mt-5'>
<input type='text' id='". $noticia['idNoticia'] ."' value='" . $noticia['idNoticia'] . "' name='idNoticia' >
<input type='text' name='imagenNoticia-guardada' value='" . $noticia['imagenNoticia'] . "'>
<input type='file' class='form-control-file mx-auto' name='imagenNoticia' id=' 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 name='tituloNoticia' type='text' class='form-control' value='" . $noticia['tituloNoticia'] . "'>
</div>

<div class='col mx-auto mb-3'>
<input name='noticiaCorta' type='text' class='form-control' value='" . $noticia['noticiaCorta'] . "'>
</div>

<div class='col mb-3'>
    <textarea name='noticiaCompleta' rows='20' cols='50' type='text' class='form-control'>" 
    . $noticia['noticiaCompleta'] . "</textarea>
</div>

<div class='d-inline-block'>
    <button class='enviarEditarNoticia btn btn-success'>EDITAR NOTICIA</button>
    <a href='index.php'><button type='button' class='btn btn-warning'>VOLVER</button></a>
</div>
</form>";
}

  }

Once I visualize the news, I edit it and I give it to the EDIT NEWS button (that your class is sendEditNewsletter ) and your AJAX the following ( TO MY LOOK THE PROBLEM IS HERE. .. I do not know how to send you the ID of the news since in DATA I am using the formData. ":

        $("#seccionEditarNoticia").on("click", ".enviarEditarNoticia", function() 
     {
        $('#formEditarNoticia').serialize();
        $.ajax({
            type: "POST",
            url: "subirNoticia.php?p=modificar",
            data: new FormData($('#formEditarNoticia')[2]),
            contentType: false,
            processData:false,
            success: function(datos) {
                $('#mensaje').empty();
                $('#mensaje').append(datos);
            }
        });
    });   

And good to click there, I should take here ...

}elseif ($accion == 'modificar') {

if (isset($_POST['id'])) {
    $id = $_POST['id'];
}

    $idNoticia = $_POST['idNoticia'];
    $imagenNoticia_guardada = $_POST['imagenNoticia-guardada'];
    $imagenNoticia = $_FILES['imagenNoticia'];
    $tituloNoticia = $_POST['tituloNoticia'];
    $noticiaCorta = $_POST['noticiaCorta'];
    $noticiaCompleta = $_POST['noticiaCompleta'];

    if (empty($imagenNoticia['name'])) {
        $imagenNoticia = $imagenNoticia_guardada;
    } else {
        $carpeta_destino = '../img/noticias/';
        $archivo_subido = $carpeta_destino . $_FILES['imagenNoticia']['name'];
        move_uploaded_file($_FILES['imagenNoticia']['tmp_name'], $archivo_subido);
        $imagenNoticia = $_FILES['imagenNoticia']['name'];
    }

        $statement = $conexion->prepare(
        "UPDATE noticias SET tituloNoticia = :tituloNoticia, noticiaCorta = :noticiaCorta, noticiaCompleta = :noticiaCompleta, imagenNoticia = :imagenNoticia WHERE idNoticia = $idNoticia"
    );

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

        echo "La noticia ha sido editada correctamente.";

     }

I did not put the complete IF code with the add or delete because it works correctly.

I hope you can give me a hand to be able to modify this. If some information is missing, or the complete codes are necessary, I edit them.

Thank you very much !!

    
asked by ZeR0ByTe 15.11.2017 в 11:48
source

1 answer

1

You have the start of the form outside the foreach loop, therefore it closes after the first news and from then on each browser will do what it pleases.

You must place it inside the loop, so you have as many forms as news and it is simpler to send an update. We also concatenate the id of the news to the id of the form to be unique.

elseif ($accion == 'editarNoticias'){

$id = $_POST['id'];

//Consulta BD Editar Noticia segun el ID.
$statement2 = $conexion->prepare("SELECT * FROM noticias WHERE idNoticia = $id");
$statement2->execute();
$noticias = $statement2->fetchAll();

//MODIFICAR DESDE ACA
echo "<h1 class='text-center m-5'>Editar noticias SB</h1>";

foreach ($noticias as $noticia) {
echo "
<form id='formEditarNoticia_" . $noticia['idNoticia'] . "' class='text-center' method='post' enctype='multipart/form-data'>
<div class='form-group mt-5'>
<input type='text' id='". $noticia['idNoticia'] ."' value='" . $noticia['idNoticia'] . "' name='idNoticia' >
<input type='text' name='imagenNoticia-guardada' value='" . $noticia['imagenNoticia'] . "'>
<input type='file' class='form-control-file mx-auto' name='imagenNoticia' id=' 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 name='tituloNoticia' type='text' class='form-control' value='" . $noticia['tituloNoticia'] . "'>
</div>

<div class='col mx-auto mb-3'>
<input name='noticiaCorta' type='text' class='form-control' value='" . $noticia['noticiaCorta'] . "'>
</div>

<div class='col mb-3'>
    <textarea name='noticiaCompleta' rows='20' cols='50' type='text' class='form-control'>" 
    . $noticia['noticiaCompleta'] . "</textarea>
</div>

<div class='d-inline-block'>
    <button class='enviarEditarNoticia btn btn-success'>EDITAR NOTICIA</button>
    <a href='index.php'><button type='button' class='btn btn-warning'>VOLVER</button></a>
</div>
</form>";
}

  }

Afterwards, in the ajax, we send the data with:

   $(".enviarEditarNoticia").click(function(event) {

    event.preventDefault();

    $.ajax({
        type: "POST",
        url: "subirNoticia.php?p=modificar",
        data: $(event.target.form).serialize(),
        contentType: false,
        processData:false,
        success: function(datos) {
            $('#mensaje').empty();
            $('#mensaje').append(datos);
        }
    });
}); 

Except for syntax errors I think the solution is more or less successful.

In the ajax script it is possible that on the part of:

if (isset($_POST['id'])) {
    $id = $_POST['id'];
}

because there is no element with name = "id" or added by javascript.

    
answered by 15.11.2018 в 14:55