elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  Problema al modificar datos - Jquery Ajax PHP
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema al modificar datos - Jquery Ajax PHP  (Leído 2,371 veces)
ka0s


Desconectado Desconectado

Mensajes: 308


Ver Perfil
Problema al modificar datos - Jquery Ajax PHP
« en: 16 Noviembre 2017, 09:53 am »

Buenos días gente, Tengo un sistema de noticias implementado. Al listar las noticias y clickear en el boton editarNoticia. Aparece la noticia con todos los campos para editar junto con un input "file" que si se edita una noticia, junto con su imagen, reemplaza a la anterior imagen que estaba subida cuando se creo la noticia.

El problema yo creo que está en el AJAX, no se que estoy haciendo mal o como llamar al ID de la noticia correspondiente. Yo ya hice el BORRAR y me funciona correctamente pero no se porque no me sale con el editar que es casi parecido.

Con esto traigo las noticias. (Esto funciona correctamente). No pongo el codigo anterior, pq no es necesario supongo.

Código
  1. elseif ($accion == 'editarNoticias'){
  2.  
  3. $id = $_POST['id'];
  4.  
  5. //Consulta BD Editar Noticia segun el ID.
  6. $statement2 = $conexion->prepare("SELECT * FROM noticias WHERE idNoticia = $id");
  7. $statement2->execute();
  8. $noticias = $statement2->fetchAll();
  9.  
  10. //MODIFICAR DESDE ACA
  11. echo "<h1 class='text-center m-5'>Editar noticias SB</h1>
  12. <form id='formEditarNoticia' class='text-center' method='post' enctype='multipart/form-data'>";
  13.  
  14. foreach ($noticias as $noticia) {
  15. echo "<div class='form-group mt-5'>
  16. <input type='text' id='". $noticia['idNoticia'] ."' value='" . $noticia['idNoticia'] . "' name='idNoticia' >
  17. <input type='text' name='imagenNoticia-guardada' value='" . $noticia['imagenNoticia'] . "'>
  18. <input type='file' class='form-control-file mx-auto' name='imagenNoticia' id=' placeholder=' aria-describedby='fileHelpId'>
  19. <small id='fileHelpId' class='form-text text-muted text-center'>Seleccione la imagen que quiere subir...</small></div>
  20.  
  21. <div class='col mx-auto mb-3'>
  22.    <input name='tituloNoticia' type='text' class='form-control' value='" . $noticia['tituloNoticia'] . "'>
  23. </div>
  24.  
  25. <div class='col mx-auto mb-3'>
  26. <input name='noticiaCorta' type='text' class='form-control' value='" . $noticia['noticiaCorta'] . "'>
  27. </div>
  28.  
  29. <div class='col mb-3'>
  30.    <textarea name='noticiaCompleta' rows='20' cols='50' type='text' class='form-control'>"
  31.    . $noticia['noticiaCompleta'] . "</textarea>
  32. </div>
  33.  
  34. <div class='d-inline-block'>
  35.    <button class='enviarEditarNoticia btn btn-success'>EDITAR NOTICIA</button>
  36.    <a href='index.php'><button type='button' class='btn btn-warning'>VOLVER</button></a>
  37. </div>
  38. </form>";
  39. }
  40.  
  41. }

Una vez que visualizo la noticia, la edito y le doy al botón EDITAR NOTICIA (que su clase es enviarEditarNoticia) y su AJAX el siguiente (A MI PARECER EL PROBLEMA ES AQUÍ... No se como enviarle el ID de la noticia ya que en DATA estoy usando el formData.":

Código
  1.        $("#seccionEditarNoticia").on("click", ".enviarEditarNoticia", function()
  2.     {
  3.        $('#formEditarNoticia').serialize();
  4.        $.ajax({
  5.            type: "POST",
  6.            url: "subirNoticia.php?p=modificar",
  7.            data: new FormData($('#formEditarNoticia')[2]),
  8.            contentType: false,
  9.            processData:false,
  10.            success: function(datos) {
  11.                $('#mensaje').empty();
  12.                $('#mensaje').append(datos);
  13.            }
  14.        });
  15.    });  

Y bueno al clickear .enviarEditarNoticia debería hacer esto:

Código
  1. }elseif ($accion == 'modificar') {
  2.  
  3. if (isset($_POST['id'])) {
  4.    $id = $_POST['id'];
  5. }
  6.  
  7.    $idNoticia = $_POST['idNoticia'];
  8.    $imagenNoticia_guardada = $_POST['imagenNoticia-guardada'];
  9.    $imagenNoticia = $_FILES['imagenNoticia'];
  10.    $tituloNoticia = $_POST['tituloNoticia'];
  11.    $noticiaCorta = $_POST['noticiaCorta'];
  12.    $noticiaCompleta = $_POST['noticiaCompleta'];
  13.  
  14.    if (empty($imagenNoticia['name'])) {
  15.        $imagenNoticia = $imagenNoticia_guardada;
  16.    } else {
  17.        $carpeta_destino = '../img/noticias/';
  18.        $archivo_subido = $carpeta_destino . $_FILES['imagenNoticia']['name'];
  19.        move_uploaded_file($_FILES['imagenNoticia']['tmp_name'], $archivo_subido);
  20.        $imagenNoticia = $_FILES['imagenNoticia']['name'];
  21.    }
  22.  
  23.        $statement = $conexion->prepare(
  24.        "UPDATE noticias SET tituloNoticia = :tituloNoticia, noticiaCorta = :noticiaCorta, noticiaCompleta = :noticiaCompleta, imagenNoticia = :imagenNoticia WHERE idNoticia = $idNoticia"
  25.    );
  26.  
  27.    $statement->execute(array(
  28.        ':tituloNoticia' => $tituloNoticia,
  29.        ':noticiaCorta' => $noticiaCorta,
  30.        ':noticiaCompleta' => $noticiaCompleta,
  31.        ':imagenNoticia' => $imagenNoticia
  32.    ));
  33.  
  34.        echo "La noticia ha sido editada correctamente.";
  35.  
  36.     }

No puse el codigo completo del IF con el agregar o borrar porque eso funciona correctamente.

He intentado muchas cosas, puedo insertar y borrar pero no puedo modificar porque no se como enviar mis nuevos valores ingresados en los input. En el insertar y borrar yo usaba el data: pero ahora en el modificar en el data tengo el data: new FormData, entonces no se como implementarlo.

Otra cosa que he notado es que cuando escribo en los input para modificar, he mirado con firebug y el atributo value= no cambia. O sea el input en el navegador ingresa mi texto, pero miro internamente y el value sigue igual que como llegó.

Espero que me puedan dar una mano, debe ser una tonteria... pero me tiene loco hace 2 dias! :(

Muchas gracias por leer!




En línea

ka0s


Desconectado Desconectado

Mensajes: 308


Ver Perfil
Re: Problema al modificar datos - Jquery Ajax PHP
« Respuesta #1 en: 16 Noviembre 2017, 11:59 am »

Creo que he avanzado algo, me di cuenta que el
Código
  1. $('#formEditarNoticia').serialize();

No hacia nada, porque mi formulario #formEditarNoticia no tenía ningún atributo name.
Ahora al darle enviar. Me arroja los errores:

Código:
Notice: Undefined index: idNoticia in C:\MAMP\htdocs\Web\admin\subirNoticia.php on line 34

Notice: Undefined index: imagenNoticia-guardada in C:\MAMP\htdocs\Web\admin\subirNoticia.php on line 35

Notice: Undefined index: imagenNoticia in C:\MAMP\htdocs\Web\admin\subirNoticia.php on line 36

Notice: Undefined index: tituloNoticia in C:\MAMP\htdocs\Web\admin\subirNoticia.php on line 37

Notice: Undefined index: noticiaCorta in C:\MAMP\htdocs\Web\admin\subirNoticia.php on line 38

Notice: Undefined index: noticiaCompleta in C:\MAMP\htdocs\Web\admin\subirNoticia.php on line 39
.

La verdad no se porque me dice eso si yo lo tengo asi:

Código
  1. elseif ($accion == 'modificar') {
  2.  
  3.        $idNoticia = $_POST['idNoticia']; //linea 34
  4.        $imagenNoticia_guardada = $_POST['imagenNoticia-guardada'];//linea 35
  5.        $imagenNoticia = $_FILES['imagenNoticia'];//linea 36
  6.        $tituloNoticia = $_POST['tituloNoticia'];//linea 37
  7.        $noticiaCorta = $_POST['noticiaCorta'];//linea 38
  8.        $noticiaCompleta = $_POST['noticiaCompleta'];//linea 39

Me esta volviendo loco esto! :(


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Como modificar para convertirlo en una encuesta? (Jquery , Ajax, Php, Mysql)
Desarrollo Web
amadeo123 1 3,399 Último mensaje 27 Diciembre 2011, 21:42 pm
por #!drvy
Problema en Jquery (ajax) « 1 2 »
Desarrollo Web
:ohk<any> 11 5,829 Último mensaje 15 Julio 2014, 23:00 pm
por MinusFour
Notificaciones con Ajax Y jQuery
Desarrollo Web
freespace16 4 5,110 Último mensaje 20 Julio 2016, 17:20 pm
por 50l3r
Duda con jQuery, Ajax, PHP
Desarrollo Web
Arm144 2 1,791 Último mensaje 10 Marzo 2017, 22:47 pm
por Herminio0
Problema con jQuery peticion Ajax
Desarrollo Web
Ali Baba 5 2,288 Último mensaje 4 Octubre 2017, 03:29 am
por Ali Baba
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines