Ver Mensaje Individual
  #1 (permalink)  
Antiguo 09/09/2010, 11:29
Stendelis
 
Fecha de Ingreso: julio-2006
Ubicación: Montevideo
Mensajes: 34
Antigüedad: 17 años, 9 meses
Puntos: 0
Enviar formulario dinámico - Jquey-PHP

Buenas,

Estoy con formulario que funciona de maravillas, pero tengo un problema al intentar emular un tipo de Hystori del navegador. Paso a esplicar con un ejemplo.

Se trata de un formulario en el cual cargo a través de jQuery un combo y hago unas cuentas y otras cosas, al darle "Submit" paso los datos a un PHP en el cual el usuario puede hacer "Back" y necesito que se recuerden los datos agregados en el formulario en la página anterior.

Por este motivo lo que hago es guardar los datos en una cookie en este PHP, si el usuario hace "Back" vía jQuery tomo los datos de la cookie, completo el formulario tal cual estaba y si yo agrego algo al formulario y hago "Submit", el formulario no pasa todos los datos traídos en la cookie, el primero no lo pasa y si agrego mas items esos si van.

Se que tendía que hacer algo asi como un live.submit, pero no veo donde ponerlo.

Pego un ejemplo funcional de mi código: se puede ver funcionando [URL="http://www.telemet.com/pruebas/"]aquí[/URL]

código formulario
Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test de formulario</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload=function(){
	
//Agregar items de un combo a otro combo y a un ul
		$("#add").click(function(){
          $('#items option:selected').each(function(){
               var nombre = $(this).text();  
               var valor = $(this).val();
			   var agregar = true;
			   
			   //verifica si ya no esta agregado
			   $('#itemsselected option').each(function(){  
               		var valor2 = $(this).val();  
					if (valor2 == valor){agregar = false;}
				});	
			   
			   //si no esta agregado lo hace
			   if (agregar){
					$("#itemsadd").append("<li id='"+valor+"'>"+nombre+" <a class='delete' href='#'>x</a></li>");
					$("#items option:selected").remove();
					$("#itemsselected").append("<option value='"+valor+"'selected='selected'>"+nombre+"</option>");
					$("#total").html("(" + parseInt($("#itemsselected option").length) +")");
			   }	
          });
          return false;
       });


//Borra los items del ul y el combo para volverlo a agregar en el combo inicial
		$("a.delete").live('click',function(){
			var parent = $(this).parent();
			$("#itemsselected").find("option[value='"+parent.attr("id")+"']").remove().appendTo("#items");
			parent.remove();
			$("#total").html("(" + parseInt($("#itemsselected option").length) +")");
			return false;
		});
		
//Luego del submit se graba cookie en php y si se hace back recargo la seleccion
		value = $.cookie("test");
			   if (value){
				  var cookieitems=value.split(",");
				  	for (i=0;i<cookieitems.length;i++){
						var valor = cookieitems[i];
						$("#itemsadd").append("<li id='"+valor+"'>"+valor+" <a class='delete' href='#'>x</a></li>");
						$("#itemsselected").append("<option value='"+valor+"'selected='selected'>"+valor+"</option>");
						$("#items").find("option[value='"+valor+"']").remove();
					}
				$("#total").html("(" + parseInt($("#itemsselected option").length) +")");
				return false;
			   }

}
</script>
</head>

<body>
<table width="700" border="1" cellpadding="20" cellspacing="10">
  <tr>
    <td width="243">
      <select name="items" size="5" multiple="multiple" id="items">
        <option value="test1">test1</option>
        <option value="test2">test2</option>
        <option value="test3">test3</option>
        <option value="test4">test4</option>
        <option value="test5">test5</option>
        <option value="test6">test6</option>
        <option value="test7">test7</option>
        <option value="test8">test8</option>
    </select>
    <br />
	<a href="#" id="add">Agregar items</a>
    </td>
    <td width="341">
    
    <form action="test.php" method="post">
        Seleccionadas: <span id="total">(0)</span><br />
        <select style="display:none;" name="itemsselected[]" id="itemsselected" multiple="multiple"></select><br />
		<input name="enviar" type="submit" id="enviar" value="Probar">
	</form>
    <ul id="itemsadd"></ul>
    </td>
  </tr>
</table>
</body>
</html> 
código archivo PHP
Código PHP:
<?php 
//verifica si se hizo submit
if($_POST['enviar'] != '') { 
    
//trae datos
    
$totselected $_POST["itemsselected"];
        if (
$totselected){
            
//cuenta el total de items
            
$total count($totselected);
            
            
//solo hago esto para obtener un string con los items
                
foreach ($totselected as $t){$totselectedlist $totselectedlist.$t.",";}
                
//le borro la última coma
                
$totselectedlist substr($totselectedlist0, -1);
        }    
    
    
//seteo cookie con el string    
    
setcookie("test" $totselectedlist time()+3600);
}
?>

Total de items
<?= $total;?>
<br>
<br>
<br>
Sting
<?= $totselectedlist;?>
<br>
<br>
Haz Back en el navegador para ver si recuperamos el listado

Última edición por Stendelis; 09/09/2010 a las 12:52