Foros del Web » Programando para Internet » Javascript » Frameworks JS »

problema con php + mysql + ajax

Estas en el tema de problema con php + mysql + ajax en el foro de Frameworks JS en Foros del Web. hola amigos me encontre un codigo para poder hacer registros en php con mysql y ajax y pues lo estuve probando y no le hayo ...
  #1 (permalink)  
Antiguo 13/05/2009, 23:34
 
Fecha de Ingreso: noviembre-2003
Ubicación: Puente de ixtla
Mensajes: 773
Antigüedad: 20 años, 6 meses
Puntos: 0
Exclamación problema con php + mysql + ajax

hola amigos me encontre un codigo para poder hacer registros en php con mysql y ajax y pues lo estuve probando y no le hayo en que esta mal. De hecho este codigo lo encontre en este foro con algo similar pero nunca respondieron el porque.

El problema es que no registra ni manda un mensaje solo se ve que por un momento al darle click en guardar del forulario aparece el div pero por muy poco tiempo pero no inserta nada.
Aqui pongo el codigo

registro_credencial.php
Código HTML:
<HTML>
<head>
<title>Registro de credencial de maestro </title>
<script type="text/javascript" src="ajax.js"></script>
</head>

<body>
<div id="Resultado"></div>  
  <form id="registro" method="POST" action="" onSubmit="GuardarRegistro(); return false">
    <table id="tabla" width="850" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="162" height="32">&nbsp;</td>
        <td width="39">&nbsp;</td>
        <td colspan="4" bgcolor="#EBEEF1">REGISTRO CREDENCIAL MAESTRO </td>
      </tr>
      <tr>
        <td height="27">&nbsp;</td>
        <td>&nbsp;</td>
        <td width="143">Nombre </td>
        <td colspan="2"><label>
          <input name="nombre" type="text" id="nombre" size="40" maxlength="255" />
        </label></td>
        <td width="233">&nbsp;</td>
      </tr>
      <tr>
        <td height="27">&nbsp;</td>
        <td>&nbsp;</td>
        <td>Apellido Paterno: </td>
        <td colspan="2"><input name="ap_materno" type="text" id="ap_paterno" size="40" maxlength="255" /></td>
      </tr>
      <tr>
        <td height="27">&nbsp;</td>
        <td>&nbsp;</td>
        <td>Apellido Materno <span class="Estilo1">:</span></td>
        <td colspan="2"><input name="ap_materno" type="text" id="ap_materno" size="40" maxlength="255" /></td>
      </tr>
      <tr>
        <td height="27">&nbsp;</td>
        <td>&nbsp;</td>
        <td>No. Credencial <span class="Estilo1">_</span></td>
        <td colspan="2"><input name="no_credencial" type="text" id="no_credencial" size="40" maxlength="12" /></td>
        <td>&nbsp;</td>
      </tr>

  <td colspan="3">&nbsp;</td>
      <td><input type="submit" name="Guardar" id="Guardar" value="Guardar..." class="bordemenu" /></td>
  </tr>
    </table>
  </form> 
</div> 
registrar_credencial.php
Código PHP:
<?
include("config.php");
$nombre=$_POST['nombre'];
$ap_paterno=$_POST['ap_paterno'];
$ap_materno=$_POST['ap_materno'];
$no_credencial=$_POST['no_credencial'];
$sql="SELECT * FROM credencial_maestro WHERE no_credencial='$no_credencial'";
$result=mysql_query($sql) or die("1 Error al intentar ejecutar la sentencia sql, mysql dice: ").mysql_error();
$num=mysql_num_rows($result);
echo 
$num;
if(
$num==0)
{
$ssql="INSERT INTO credencial_maestro(no_credencial,nombre,ap_paterno,ap_materno) VALUES('".$no_credencial."','".$nombre."','".$ap_paterno."','".$ap_materno."')";
$res=mysql_query($ssql) or die("2 Error al intentar insertar los datos , mysqk dice: ").mysql_error();
echo 
"Los datos se han insertado correctamente";
echo 
$num;
}else{
echo 
"Error el numero de credencial ya existe";
}
?>
ajax.js
Código HTML:
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; 
} 

function GuardarRegistro(){ 
  //donde se mostrará lo resultados 
  divResultado = document.getElementById('Resultado'); 
  divResultado.innerHTML= '<img src="loading.gif">'; 
  //valores de las cajas de texto 
  nombre=document.registro.nombre.value; 
  ap_paterno=document.registro.ap_paterno.value; 
  ap_materno=document.registro.ap_materno.value; 
  no_credencial=document.registro.no_credencial.value; 

//instanciamos el objetoAjax 

    ajax=objetoAjax(); 
  //uso del medoto POST 
  //archivo que realizará la operacion 
  //registro.php 
  ajax.open("POST", "registrar_credencial.php",true); 
  ajax.onreadystatechange=function() { 
  if (ajax.readyState==4) { 
  //mostrar resultados en esta capa 
  divResultado.innerHTML = ajax.responseText 
  //llamar a funcion para limpiar los inputs 
  LimpiarCampos(); 
  } 
  } 

  ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
  //enviando los valores 
  ajax.send("nombre="+nombre+"&ap_paterno="+ap_paterno+"&ap_materno="+ap_materno+"&no_credencial="+no_credencial) 
} 

function LimpiarCampos(){ 
  document.registro.nombre.value=""; 
  document.registro.ap_paterno.value=""; 
  document.registro.ap_materno.value=""; 
  document.registro.no_credencial.value=""; 

  document.registro.nombre.focus(); 
}  
__________________
°º¤ø,¸¸,ø¤º°`°º¤ø,¸S@M°º¤ø,¸¸,ø¤º°`°º¤ø,¸.
Dios solo nos dio el 0 y el 1 y con solo eso hemos construido un universo
  #2 (permalink)  
Antiguo 14/05/2009, 03:06
 
Fecha de Ingreso: julio-2008
Ubicación: Alcañiz-Teruel-España
Mensajes: 182
Antigüedad: 15 años, 9 meses
Puntos: 5
Respuesta: problema con php + mysql + ajax

Buenas

No es document.registro ,es document.forms.registro

Por otro lado en vez de hacer esto

Código html:
Ver original
  1. <form id="registro" method="POST" action="" onSubmit="GuardarRegistro(); return false">

debes poner la llamada a la funcion javascript en el action del form

Código html:
Ver original
  1. <form id="registro" method="POST" action="javascript:GuardarRegistro();">

Yo he probado este codigo y me funciona

Código javascript:
Ver original
  1. function objetoAjax(){
  2.     var xmlhttp=false;
  3.     try {
  4.         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  5.     } catch (e) {
  6.         try {
  7.            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  8.         } catch (E) {
  9.             xmlhttp = false;
  10.           }
  11.     }
  12.  
  13.     if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  14.         xmlhttp = new XMLHttpRequest();
  15.     }
  16.     return xmlhttp;
  17. }
  18.  
  19. function GuardarRegistro(){
  20.   //donde se mostrará lo resultados
  21.   divResultado = document.getElementById('Resultado');
  22.   divResultado.innerHTML= '<img src="wait.gif">';
  23.   //valores de las cajas de texto
  24.   nombre=document.forms.registro.nombre.value;
  25.   ap_paterno=document.forms.registro.ap_paterno.value;
  26.   ap_materno=document.forms.registro.ap_materno.value;
  27.   no_credencial=document.forms.registro.no_credencial.value;
  28.  
  29.   //instanciamos el objetoAjax
  30.  
  31.   ajax=objetoAjax();
  32.   //uso del medoto POST
  33.   //archivo que realizará la operacion
  34.   //registro.php
  35.   ajax.open("POST", "registro.php",true);
  36.   ajax.onreadystatechange=function() {
  37.     if (ajax.readyState==4) {
  38.     //mostrar resultados en esta capa
  39.     divResultado.innerHTML = ajax.responseText
  40.     //llamar a funcion para limpiar los inputs
  41.     LimpiarCampos();
  42.     }
  43.   }
  44.   ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  45.   //enviando los valores
  46.   ajax.send("nombre="+nombre+"&ap_paterno="+ap_paterno+"&ap_materno="+ap_materno+"&no_credencial="+no_credencial)
  47. }
  48.  
  49. function LimpiarCampos(){
  50.   document.forms.registro.nombre.value="";
  51.   document.forms.registro.ap_paterno.value="";
  52.   document.forms.registro.ap_materno.value="";
  53.   document.forms.registro.no_credencial.value="";
  54.  
  55.   document.forms.registro.nombre.focus();
  56. }


Código html:
Ver original
  1. <title>Registro de credencial de maestro </title>
  2. <script type="text/javascript" src="ajax.js"></script>
  3. </head>
  4.  
  5. <div id="Resultado"></div>  
  6.   <form id="registro" method="POST" action="javascript:GuardarRegistro();">
  7.     <table id="tabla" width="850" border="0" cellpadding="0" cellspacing="0">
  8.       <tr>
  9.         <td width="162" height="32">&nbsp;</td>
  10.         <td width="39">&nbsp;</td>
  11.         <td colspan="4" bgcolor="#EBEEF1">REGISTRO CREDENCIAL MAESTRO </td>
  12.       </tr>
  13.       <tr>
  14.         <td height="27">&nbsp;</td>
  15.         <td>&nbsp;</td>
  16.         <td width="143">Nombre </td>
  17.         <td colspan="2"><label>
  18.           <input name="nombre" type="text" id="nombre" size="40" maxlength="255" />
  19.         </label></td>
  20.         <td width="233">&nbsp;</td>
  21.       </tr>
  22.       <tr>
  23.         <td height="27">&nbsp;</td>
  24.         <td>&nbsp;</td>
  25.         <td>Apellido Paterno: </td>
  26.         <td colspan="2"><input name="ap_materno" type="text" id="ap_paterno" size="40" maxlength="255" /></td>
  27.       </tr>
  28.       <tr>
  29.         <td height="27">&nbsp;</td>
  30.         <td>&nbsp;</td>
  31.         <td>Apellido Materno <span class="Estilo1">:</span></td>
  32.         <td colspan="2"><input name="ap_materno" type="text" id="ap_materno" size="40" maxlength="255" /></td>
  33.       </tr>
  34.       <tr>
  35.         <td height="27">&nbsp;</td>
  36.         <td>&nbsp;</td>
  37.         <td>No. Credencial <span class="Estilo1">_</span></td>
  38.         <td colspan="2"><input name="no_credencial" type="text" id="no_credencial" size="40" maxlength="12" /></td>
  39.         <td>&nbsp;</td>
  40.       </tr>
  41.  
  42.   <td colspan="3">&nbsp;</td>
  43.       <td><input type="submit" name="Guardar" id="Guardar" value="Guardar..." class="bordemenu" /></td>
  44.   </tr>
  45.     </table>
  46.   </form>
  47. </div>

Código php:
Ver original
  1. //include("config.php");
  2. //$nombre=$_POST['nombre'];
  3. //$ap_paterno=$_POST['ap_paterno'];
  4. //$ap_materno=$_POST['ap_materno'];
  5. //$no_credencial=$_POST['no_credencial'];
  6. //$sql="SELECT * FROM credencial_maestro WHERE no_credencial='$no_credencial'";
  7. //$result=mysql_query($sql) or die("1 Error al intentar ejecutar la sentencia sql, mysql dice: ").mysql_error();
  8. //$num=mysql_num_rows($result);
  9. //echo $num;
  10. //if($num==0)
  11. //{
  12. //$ssql="INSERT INTO credencial_maestro(no_credencial,nombre,ap_paterno,ap_materno) VALUES('".$no_credencial."','".$nombre."','".$ap_paterno."','".$ap_materno."')";
  13. //$res=mysql_query($ssql) or die("2 Error al intentar insertar los datos , mysqk dice: ").mysql_error();
  14. //echo "Los datos se han insertado correctamente";
  15. //echo $num;
  16. //}else{
  17. //echo "Error el numero de credencial ya existe";
  18. //}
  19. echo $nombre=$_POST['nombre'];
  20. echo '<br>';
  21. echo $ap_paterno=$_POST['ap_paterno'];
  22. echo '<br>';
  23. echo $ap_materno=$_POST['ap_materno'];
  24. echo '<br>';
  25. echo $no_credencial=$_POST['no_credencial'];

Si tienes problemas de acentos y caracteres especiales prueba añadiendo esto en el documento php que envias al servidor por medio de ajax

Código php:
Ver original
  1. header('Content-Type: text/xml; charset=ISO-8859-1');

De esta forma

Código php:
Ver original
  1. header('Content-Type: text/xml; charset=ISO-8859-1');
  2.  
  3. include("config.php");
  4. $nombre=$_POST['nombre'];
  5. $ap_paterno=$_POST['ap_paterno'];
  6. $ap_materno=$_POST['ap_materno'];
  7. ...
  8. ...
  9. ...
  10. ...

Saludos
__________________
Si quieres puedes y si puedes debes. Imposible is nothing!!!

Última edición por matak; 14/05/2009 a las 03:21
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:00.