JQuery tiene una función llamada serializeArray que guarda el formulario en un array con el nombre del elemento y el valor. Luego simplemente con la función post envias el array y puedes actualizar el div con la respuesta del servidor.
ok me aclarare por si acaso: Tengo dos .php 1 inserta los elemntos en la base de datos y el otro los carga en una pagina y los actualizo con ajax, lo quye quiero es con ajax enviar los datos a la base de datos sin tener que actualizar la pagina
Ajax:
Código
function objetoAjax(){ var xmlhttp=false; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } //Función para recoger los datos del formulario y enviarlos por post function enviarDatosEmpleado(){ divResultado = document.getElementById('contenedor'); mensaje=document.from.mensaje.value; ajax=objetoAjax(); ajax.open("POST", "ingresar.php",true); ajax.onreadystatechange=function() { if (ajax.readyState==4) { divResultado.innerHTML = ajax.responseText LimpiarCampos(); } } ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); ajax.send("mensaje="+mensaje); } function LimpiarCampos() { document.form.mensaje.value=""; }
ingresar.php
Código
require("connect_db.php"); $nombre = $_SESSION['usuario']; $mensaje = $_POST['mensaje'];
cargar.php
Código
<?php require("connect_db2.php"); $colo = "#320EF8"; function mostrarDatos($resultados ,$color) { if($resultados !=NULL){ echo "<p style='display: inline; color: $color; font-size: 120%; margin-left: 8px;'>".$resultados['nombre']."</p>"; echo ": "; echo $resultados['mensaje']; echo "</br>"; echo "-------------------------------------------------------------------"; echo "</br>"; } else { echo "<br/>No hay mas datos<br/>"; } } mostrarDatos($fila, $colo); }
pagina:
Código
<html> <head> <link rel="stylesheet" type="text/css" href="chat.css"> <link rel="stylesheet" type="text/css" href="inicio.css"> </head> <body background="fondos/fondo-inicio.jpg""> <ul> <ul style="float:right;list-style-type:none;"> </ul> </ul> <div id="contenedor"> </div> <form action="" method="POST" name="form" onsubmit="enviarDatosEmpleado(); return false"> <input type="text" id="mensaje" name="mensaje"> <input type="submit" id="boton" value="Enviar"> </form> <script > </script> </body> </html>