Foros del Web » Programando para Internet » Jquery »

Envio de formulario con jquery sin boton submit

Estas en el tema de Envio de formulario con jquery sin boton submit en el foro de Jquery en Foros del Web. Necesito enviar un formulario desde una página sin utilizar el botón submit. Pero además necesito que no se cambie la URL. Por lo cual opté ...
  #1 (permalink)  
Antiguo 02/10/2010, 03:41
 
Fecha de Ingreso: diciembre-2007
Mensajes: 17
Antigüedad: 16 años, 4 meses
Puntos: 0
Envio de formulario con jquery sin boton submit

Necesito enviar un formulario desde una página sin utilizar el botón submit. Pero además necesito que no se cambie la URL. Por lo cual opté por utilizar jquery. Específicamente intento hacerlo con axajForm.
No funciona.

Si utilizo un botón submit funciona sin problemas. Pero en la página desde donde tiene que enviarse no puede haber ningún botón. El formulario está compuesto por campos ocultos y esto es totalmente transparente para el usuario.

Agredecería muchísimo si alguien me puede dar o una solución con estas mismas herramientas o alguna sugerencia con otro tipo de herramientas.

Pongo el código (simplificado) para que se vea como estoy intentando hacerlo.

Cita:
<!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>Documento sin título</title>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
// target: '#output1', // target element(s) to be updated with server response
beforeSubmit: cargodatos, // pre-submit callback
success: showResponse // post-submit callback

// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit

// $.ajax options can be used here too, for example:
//timeout: 3000
};

// bind form using 'ajaxForm'
$('#frmcookie').ajaxForm(options);
});


// post-submit callback
function showResponse(responseText) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property

// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property

// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server

alert('respuesta: ' + responseText);
}


function cargodatos() {
document.frmcookie.source.value = "hola";
document.frmcookie.medium.value = "adios";
document.frmcookie.term.value = "jejeje";
document.frmcookie.content.value = "jijiji";
return true;
}

</script>
</head>

<body>

<form name="frmcookie" id="frmcookie" method="post" action="recibe.php">
<input type="hidden" name="source" id="source" />
<input type="hidden" name="medium" id="medium" />
<input type="hidden" name="term" id="term" />
<input type="hidden" name="content" id="content" />
<input type="hidden" name="campaign" id="campaign" />
<input type="hidden" name="segment" id="segment" />


</form>

<script>document.frmcookie.submit(); alert('hola');</script>
</body>
</html>
recibe.php
Cita:
<?php
$source = $_POST['source'];
$medium = $_POST['medium'];
$term = $_POST['term'];
$content = $_POST['content'];

echo $source."<br />";
echo $medium."<br />";
echo $term."<br />";
echo $content."<br />";

?>
Gracias por la ayuda.
  #2 (permalink)  
Antiguo 02/10/2010, 08:38
Avatar de mayid
Colaborador
 
Fecha de Ingreso: marzo-2009
Ubicación: BsAs
Mensajes: 4.014
Antigüedad: 15 años, 1 mes
Puntos: 101
Respuesta: Envio de formulario con jquery sin boton submit

Sin usar plugins, en jquery tenes varias formas de enviar un formulario:
http://www.anieto2k.com/2009/08/18/5...ax-con-jquery/
http://www.cristalab.com/tutoriales/...-jquery-c226l/

Para disparar el evento haces:

$("#frmcookie").submit();
  #3 (permalink)  
Antiguo 02/10/2010, 08:59
 
Fecha de Ingreso: diciembre-2007
Mensajes: 17
Antigüedad: 16 años, 4 meses
Puntos: 0
Respuesta: Envio de formulario con jquery sin boton submit

mayid, muchas gracias.
Perdoná pero en este momento estoy con la cabeza hecha un zapallo de tanto darle vueltas al asunto y, como es evidente, no domino ajax ni jquery. Así que no tengo mas remedio que preguntar: ¿donde y como pongo el $("#frmcookie").submit() para disparar el evento?

Mientra tanto voy a leerme lo que hay en los enlaces que me dejaste.

Gracias de nuevo.
  #4 (permalink)  
Antiguo 02/10/2010, 10:55
Avatar de mayid
Colaborador
 
Fecha de Ingreso: marzo-2009
Ubicación: BsAs
Mensajes: 4.014
Antigüedad: 15 años, 1 mes
Puntos: 101
Respuesta: Envio de formulario con jquery sin boton submit

Según vi en tu codigo, lo que querés es que se ejecute al cargar la pagina. Entonces, ponelo dentro de document.ready.

Con disparar el evento me refería a enviar el formulario, que por defecto se hace sin ajax.

Para usar un metodo ajax (siempre y cuando no estes enviando archivos adjuntos) podes hacer así:


Código Javascript:
Ver original
  1. $.post("recibe.php", $("#frmcookie").serialize() );

ref: http://api.jquery.com/jQuery.post/

  #5 (permalink)  
Antiguo 03/10/2010, 13:47
 
Fecha de Ingreso: diciembre-2007
Mensajes: 17
Antigüedad: 16 años, 4 meses
Puntos: 0
Respuesta: Envio de formulario con jquery sin boton submit

Para que quede constancia a quien la pueda interesar el tema el código funcionando quedó así:


El que envía los datos:
Cita:
<!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>Documento sin título</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

</head>

<body>
<p>Envio de datos</p>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "recibe2.php",
data: "source=dato1&medium=dato2&term=dato3&content=dato 4",
success: function(datos){
alert("datos enviados"+datos);
}
});
})
</script>

</body>
</html>

El que recibe los datos y los almacena:
Cita:
<?php
$connectid = mysql_connect("localhost","localhost","password");
mysql_select_db("base_prueba",$connectid);


$source = $_POST['source'];
$medium = $_POST['medium'];
$term = $_POST['term'];
$content = $_POST['content'];

echo $source."<br />";
echo $medium."<br />";
echo $term."<br />";
echo $content."<br />";

$ssql = "Insert into datcookie (source,medium,term,content) values ('$source','$medium','$term','$content')";
$resp = mysql_query($ssql);

?>
Como se puede ver es algo mucho mas sencillo que lo planteado inicialmente.
Es aquello del KISS (Keep It Simple Stupid)
  #6 (permalink)  
Antiguo 04/10/2010, 07:14
Avatar de mayid
Colaborador
 
Fecha de Ingreso: marzo-2009
Ubicación: BsAs
Mensajes: 4.014
Antigüedad: 15 años, 1 mes
Puntos: 101
Respuesta: Envio de formulario con jquery sin boton submit

Que bueno lo solucionaras. Acordate que la funcion ajax del tipo Post también puede escribirse así:

Código Javascript:
Ver original
  1. $.post("recibe2.php", $("#frmcookie").serialize(),
  2.  function(datos){alert("datos enviados"+datos);
  3. } );

http://api.jquery.com/jQuery.post/

Y que serialize te prepara todos los contenidos del formulario automaticamente:

http://api.jquery.com/serialize/

Etiquetas: envio, submit, botones, formulario
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 14:12.