Foros del Web » Programando para Internet » PHP »

guardar datos dinamicos creados por ajax

Estas en el tema de guardar datos dinamicos creados por ajax en el foro de PHP en Foros del Web. hola a todos .... tengo una gran pregunta.... acabo de hacer una lista desplegable con ajax ... cuando la persona elije un tipo de auto ...
  #1 (permalink)  
Antiguo 23/06/2011, 15:20
 
Fecha de Ingreso: junio-2011
Mensajes: 26
Antigüedad: 12 años, 10 meses
Puntos: 0
guardar datos dinamicos creados por ajax

hola a todos ....

tengo una gran pregunta.... acabo de hacer una lista desplegable con ajax ... cuando la persona elije un tipo de auto se despliega automaticamente el tipo de carroceria....

mi pregunta es como puedo guardar el valor del tipo de carroceria....

mi tabla datos_auto
Código MySQL:
Ver original
  1. CREATE TABLE `datos_auto` (
  2.   `id` int(11) NOT NULL auto_increment,
  3.   `nuevo` varchar(10) NOT NULL,
  4.   `carroceria` varchar(100) NOT NULL,
  5.   `modelo` varchar(100) NOT NULL,
  6.   `ano` int(11) NOT NULL,
  7.   `patente` varchar(100) NOT NULL,
  8.   `tipo_vehi` varchar(100) NOT NULL,
  9.   `marca` varchar(100) NOT NULL,
  10.   `precio` int(20) NOT NULL,
  11.   `otro` varchar(1000) NOT NULL,
  12.   `img1` blob NOT NULL,
  13.   `radio` varchar(10) NOT NULL,
  14.   `alarma` varchar(10) NOT NULL,
  15.   PRIMARY KEY  (`id`)

tb tipo de vehiculos

Código MySQL:
Ver original
  1. CREATE TABLE `tipo_vehi` (
  2.   `id` int(11) NOT NULL auto_increment,
  3.   `nombre` varchar(100) NOT NULL,
  4.   PRIMARY KEY  (`id`)
  5. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
  6.  
  7. --
  8. -- Volcar la base de datos para la tabla `tipo_vehi`
  9. --
  10.  
  11. INSERT INTO `tipo_vehi` VALUES (1, 'vehiculo');
  12. INSERT INTO `tipo_vehi` VALUES (2, 'moto');

y mi codigo

Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <script language="javascript" type="text/javascript" src="js/js.js">
  5.  
  6. function valida(){
  7. var maximo ="2012"
  8.  
  9. // verifica si el campo marca esta vacia
  10. if (document.formulario.marca.value==""){
  11.  alert("Debe Escribir La Marca Del Vehiculo.");
  12.  return false;
  13. }
  14.  
  15. // verifica si el campo modelo esta vacio
  16. if (document.formulario.modelo.value==""){
  17.  alert("Debe Escribir El Modelo Del Vehiculo.");
  18.  return false;
  19. }
  20.  
  21. // verifica si el campo añp esta vacio
  22. if (document.formulario.ano.value==""){
  23.  alert("Debe Escribir El Año Del Vehiculo.");
  24.  return false;
  25. }
  26.  
  27. // verifica si el campo año es numerico
  28. if (!IsNumeric(document.formulario.ano.value)){
  29.  alert("El Año del Vehiculo Debe Contener Solamente Numeros.");
  30.  return false;
  31. }
  32.  
  33. // verifica si el campo año esta entre los años 1900 y el valor del maximo(2012)
  34. if ((document.formulario.ano.value<1900)||(document.formulario.ano.value>maximo)){
  35.  alert("EL Año Del Vehiculo Debe Ser Entre 1990 y "+maximo".");
  36.  return false;
  37. }
  38.  
  39. // verifica si el campo patente esta vacio
  40. if ((document.formulario.patente.value==""){
  41.  alert("Debe Ingresar La Patente De Su Vehiculo.");
  42. return false;
  43. }
  44. // verifica si el campo precio es numerico
  45. if (!IsNumeric(document.formulario.precio.value)){
  46.  alert("Debe contener Solamente Numeros.");
  47.  return false;
  48. }
  49. // verifica si el campo precio esta vacio
  50. if (document.formulario.precio.value==""){
  51.  alert("Debe Ingresar El Precio Del Vehiculo.");
  52.  return false;
  53. }else{
  54.     document.formulario.precio.value=retInt(document.formulario.precio.value)
  55. }
  56.  
  57. // Verificamos si la patente y el tipo de vehiculo es correcto
  58. function RvalPat(sValor){
  59. var ret = "";
  60.     if ((document.formulario.tipo.value=="A")||(document.formulario.tipo.value=="M"){
  61.         if ((document.formulario.patente.value.length<6)){
  62.             alert("La Patente Le Faltan Valores. Debe Contener 6 Caracteres.");
  63.             ret=""
  64.         }else{
  65.             ret = valPat(sValor);
  66.         }
  67.  
  68.     }else{
  69.         ret = sValor;
  70.  
  71.         }
  72.     return ret;
  73. }
  74. // verificacion para saber si la patente contiene numeros y letras
  75. function valPat(fieldValue){
  76. // LLNNNN o LLLLNN (donde X=letra, N=Numero). :/  me pregunto donde esta la X
  77.  var ClearfieldValue ="";
  78.  var iChars="1234567890";
  79.  var aChars = /[(A-Z)|(a-z)]/ ;
  80.     if (aChars.test(fieldValue.charAt(3)) ){
  81.         // SIGNIFICA que el 4 caracter es una letra entre a y Z
  82.         // Ahora veremos si los 4 primeros cumplen la misma funcion
  83.  
  84.         if ((aChars.test(fieldValue.charAt(0))) && (aChars.test(fieldValue.charAt(1))) && (aChars.test(fieldValue.charAt(2))) && (aChars.test(fieldValue.charAt(3)))){
  85.          // AHORA COMPROBAMOS LOS 2 ultimos caracteres para que sean numericos.
  86.             if ((!(iChars.indexOf(fieldValue.charAt(4)) == -1)) && (!(iChars.indexOf(fieldValue.charAt(5)) == -1))){
  87.                 // TODO OK entonces RETORNAMOS con MAYUSCULAS
  88.                 ClearfieldValue = fieldValue.toUpperCase()
  89.             }
  90.         }
  91.     }else{
  92.         if (aChars.test(fieldValue.charAt(1)) ){
  93.         // SIGNIFICA que el 2 caracter es una letra entre a y Z
  94.         // Ahora veremos si los 2 primeros cumplen la misma funcion
  95.         if ((aChars.test(fieldValue.charAt(0))) && (aChars.test(fieldValue.charAt(1)))){
  96.              // AHORA COMPROBAMOS LOS 4 ultimos caracteres para que sean numericos.
  97.                 if ((!(iChars.indexOf(fieldValue.charAt(2)) == -1)) && (!(iChars.indexOf(fieldValue.charAt(3)) == -1)) && (!(iChars.indexOf(fieldValue.charAt(4)) == -1)) && (!(iChars.indexOf(fieldValue.charAt(5)) == -1))){
  98.                     // TODO OK entonces RETORNAMOS con MAYUSCULAS
  99.                     ClearfieldValue = fieldValue.toUpperCase()
  100.                 }
  101.             }
  102.  
  103.         }
  104.  
  105.     }
  106. return ClearfieldValue;
  107. }
  108. function retInt(fieldValue) {
  109.  var i=0;
  110.  var ClearfieldValue ="";
  111.  var iChars="1234567890";
  112.  for (i=0; i < fieldValue.length;i++) {
  113.    if (!(iChars.indexOf(fieldValue.charAt(i)) == -1)) {
  114.         ClearfieldValue = ClearfieldValue+""+ fieldValue.charAt(i);
  115.    }
  116.  }
  117.  return ClearfieldValue;
  118. }
  119. }
  120. <title>Pagina De Muestra</title>
  121. <style type="text/css">
  122. <!--
  123. .Estilo1 {
  124.     color: #FF0000;
  125.     font-size:14px;
  126.     font-family:Arial, Helvetica, sans-serif;
  127.     }
  128. .Estilo5 {color: #666666}
  129. -->
  130. </style></head>
  131.  
  132. <h1 align="center">Registrar Vehiculo</h1>
  133. <hr color="#666666"/>
  134. <br />
  135. <div align="right"><strong class="Estilo1">(*)<span class="Estilo5"> - Campos Obligatorios</span></strong></div><br/>
  136. <table align="center" border="1" width="90%" bgcolor="#CCCCCC">
  137. <form method="post" name="formulario" action="insertar.php">
  138.         <tr>
  139.           <td width="105"><strong class="Estilo1">Vehiculo Nuevo</strong></td>
  140. <td width="171">&nbsp;<select name="nuevo">Seleccione Una Opcion...
  141.                                     <option value="no">NO</option>
  142.                                     <option value="si">SI</option>
  143.           </select></td>
  144.            <td width="105"><strong class="Estilo1">Tipo Vehiculo(*)</strong></td>
  145.           <td width="171">&nbsp;<?php include ('tipo_vehiculo.php');?></td>
  146.         </tr>
  147.         <tr>
  148.             <td width="105"><strong class="Estilo1">Carroceria(*)</strong></td>
  149.           <td width="171"><div id="resultado"></div></td>
  150.            
  151.             <td width="105"><strong class="Estilo1">Marca(*)</strong></td>
  152.           <td width="171">&nbsp;<input type="text" name="marca" /></td>
  153.         </tr>
  154.         <tr>
  155.             <td width="105"><strong class="Estilo1">Modelo(*)</strong></td>
  156.           <td width="171">&nbsp;<input type="text" name="modelo" /></td>
  157.            
  158.             <td width="105"><strong class="Estilo1">Año(*)</strong></td>
  159.           <td width="171">&nbsp;<input type="text" name="ano" size="8" /></td>
  160.         </tr>
  161.          <tr>
  162.             <td width="105"><strong class="Estilo1">Patente(*)</strong></td>
  163.            <td width="171">&nbsp;<input type="text" name="patente" size="8" maxlength="6" onBlur="this.value = RvalPat(this.value)"/></td>
  164.            
  165.             <td width="105"><strong class="Estilo1">Precio(*)</strong></td>
  166.            <td width="171">&nbsp;<input type="text" name="pesos" maxlength="11" onBlur="this.value=retInt(this.value)"/></td>
  167.         </tr>
  168.         <tr>
  169.             <td width="105"><strong class="Estilo1">Otro</strong></td>
  170.             <td width="171" align="center"><textarea name="otro" rows=4 cols=40 ></TEXTAREA></FONT></td>
  171.             <td width="105"><strong class="Estilo1">Radio</strong></td>
  172.             <td width="171" align="center"><input type="checkbox" name="radio" /></td>
  173.     </tr>
  174.         <tr>
  175.             <td width="105"><strong class="Estilo1">Imagen</strong></td>
  176.             <td width="171">&nbsp;<input type="file" name="imagen " /></td>
  177.             <td width="105"><strong class="Estilo1">Alarma</strong></td>
  178.             <td width="171" align="center"><input type="checkbox" name="alarma"/></td>            
  179.         </tr>
  180.         <tr>
  181.             <td></td>
  182.             <td><input type="submit" value="Enviar" onclick="valida()"></td>
  183.         </tr>
  184.   </form>
  185. <br />
  186. <br />
  187. </body>
  188. </html>

aca es donde lo guardo...

Código PHP:
Ver original
  1. <?php
  2. include('conexion.php');
  3.  
  4. $nuevo = $_POST['nuevo'];
  5. $tipovehi = $_POST['tipo'];
  6. $carroceria = $_POST['carroceria'];
  7. $marca = $_POST['marca'];
  8. $modelo = $_POST['modelo'];
  9. $ano = $_POST['ano'];
  10. $patente = $_POST['patente'];
  11. $precio = $_POST['precio'];
  12. $otro = $_POST['otro'];
  13. $radio = $_POST['radio'];
  14. $alarma = $_POST['alarma'];
  15. $ruta = $_FILES['imagen']['name'];
  16.  
  17. $inserta = "INSERT INTO datos_auto (nuevo, carroceria, modelo, ano, patente, tipo_vehi, marca, precio, otro, img1, radio, alarma) VALUES ('$nuevo','$carroceria','$modelo','$ano','$patente','$tipovehi','$marca','$precio','$otro','$ruta','$radio','$alarma')";
  18. $consulta = "SELECT * FROM datos_auto WHERE patente = '$patente'";
  19.  
  20. $sql = mysql_query($consulta);
  21. $numRegistro = mysql_num_rows($sql);
  22.  
  23. if($numRegistro == 1)
  24.     {
  25.         echo"<script type='text/javascript'>
  26.                 alert('EL Codigo Esta En La Base De Datos');
  27.                 window.location='registro_vehiculo.php';
  28.             </script>";
  29.     }
  30. else
  31.     {
  32.         $result = mysql_query($inserta);
  33.  
  34.             echo"<script type='text/javascript'>
  35.                     alert('Datos Del Automovil Ingresado correctamente');
  36.                     window.location='registro_vehiculo.php';
  37.                 </script>";
  38.     }
  39.  
  40.  
  41. ?>

Le ago un print_r($_POST) para saber que me esta tirando pero no me muestra el valor del select de la carroceria

gracias
  #2 (permalink)  
Antiguo 23/06/2011, 15:38
 
Fecha de Ingreso: abril-2009
Ubicación: Colombia
Mensajes: 949
Antigüedad: 15 años
Puntos: 27
Respuesta: guardar datos dinamicos creados por ajax

Si los valores de tipo de carroceria los tienes en una tabla, te pasara el nombre del tipo de carroceria, entonces antes de hacer el INSERT, debes consultar el Codigo de tipo de carroceria

Seguro le hiciste
Código PHP:
Ver original
  1. echo $carroceria; //que me imagino es el tipo de carroceria

Hazlo y dime que muestra....
  #3 (permalink)  
Antiguo 23/06/2011, 17:21
 
Fecha de Ingreso: junio-2011
Mensajes: 26
Antigüedad: 12 años, 10 meses
Puntos: 0
Respuesta: guardar datos dinamicos creados por ajax

GRACIAS X AYUDARME MIRA...

ESTA ES LA PAGINA QUE INCLUYO EN EL FORMULARIO..

TIPO_VEHICULO.PHP

Código PHP:
Ver original
  1. <?php
  2. require('conexion.php');
  3.  
  4. $sql = mysql_query("SELECT * FROM tipo_vehi ORDER BY id")
  5. ?>
  6. <select name="tipo"  onChange="pedirDatos();">
  7.     <option>Seleccione Una Opcion...</option>
  8.     <?php
  9.             while($row = mysql_fetch_array($sql)){
  10.                 echo "<option value='".$row['id']."'>".$row['nombre']."</option>";
  11.                 }
  12.      ?>
  13. </select>

LLAMA A LA UNA FUNCION EN AYAX...

JS.JS

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 pedirDatos(){
  20.         //donde se mostrará el resultado
  21.         divResultado = document.getElementById('resultado');
  22.         //tomamos el valor de la lista desplegable
  23.         nom=document.formulario.tipo.value;
  24.  
  25.         //instanciamos el objetoAjax
  26.         ajax=objetoAjax();
  27.         //usamos el medoto POST
  28.         //archivo que realizará la operacion
  29.         ajax.open("POST", "datoscarroceria.php",true);
  30.         ajax.onreadystatechange=function() {
  31.                 if (ajax.readyState==4) {
  32.                         //mostrar resultados en esta capa
  33.                         divResultado.innerHTML = ajax.responseText
  34.                 }
  35.         }
  36.         ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  37.         //enviando los valores
  38.  ajax.send("id="+nom)
  39. }

ME LO GUARDA EN LA ETIQUETA DIV NAME="RESULTADO" EN EL FORMULARIO PRINCIPAL.
RESCATA LOS DATOS DEl select name ="tipo" (TIPO_VEHICULO.PHP)
Y ME MANDA A

datoscarroceria.php

Código PHP:
Ver original
  1. <?php
  2. require('conexion.php');
  3.  
  4. $id = $_POST['id'];
  5.  
  6. $sql=mysql_query("SELECT nombre FROM carroceria WHERE id_tipo ='$id'");
  7. //mostrando el resultado
  8. ?>
  9. <select name="carroceria">
  10.     <option>Seleccione Una Opcion...</option>
  11.     <?php
  12.             while($row = mysql_fetch_array($sql)){
  13.                 echo "<option value='".$row['id']."'>".$row['nombre']."</option>";
  14.                 }
  15.      ?>
  16. </select>
  17. </body>
  18. </html>


ESTO ES LO QUE TENGO .. AL MOMENTO DE GRABAR NO LO GRABA PORQUE NO LO PASA EL VALOR DE EL SELECT DE LA CARROCERIA...

GRACIAS
  #4 (permalink)  
Antiguo 24/06/2011, 00:39
 
Fecha de Ingreso: junio-2011
Mensajes: 26
Antigüedad: 12 años, 10 meses
Puntos: 0
Respuesta: guardar datos dinamicos creados por ajax

no compadre ya encontre el desperfecto.. muchas gracias de ante mano

Etiquetas: ajax, dinamicos
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:57.