Ajax + JQuery com 2 submits pro mesmo form

3 respostas
W

Bom dia,

Tenho um formulário com dois botões e preciso que ele seja enviado para caminhos diferentes de acordo com o botão que foi clicado, estou tentando usar ajax + jquery.
So que do modo que eu testei ate agora ele sempre se amarra no primeiro botão que eu clicar, mesmo se eu clicar no outro ele executa a função do primeiro botão clicado.
Segue o codigo:

<html>
<head>
	<script type="text/javascript" src="../jquery/js/jquery-1.8.3.js"></script>
	<script type="text/javascript" src="../jquery/js/jquery-ui-1.9.2.custom.min.js">
	</script><link type="text/css" href="../jquery/css/redmond/jquery-ui-1.9.2.custom.css" rel="stylesheet"/>
	<script type="text/javascript">	
	jQuery(document).ready(function(){				
		var requestRunning = false;
		
		$( "#enviar" ).button().click(function() {
			if (requestRunning) {
				return;
			}
						
			jQuery('#ajax_form').submit(function(){
				var dados = jQuery( this ).serialize();				
				var opt1 = {
					type: "POST",
					url: "processa.php",					
					cache: false,
					success: function(){						
						alert( "teste 1" );
					}
				};
				requestRunning = true;
				$.ajax(opt1);								
				return false;				
			});			
		});
			
		$( "#testar" ).button().click(function() {			
			if (requestRunning) {
				return;
			}
						
			jQuery('#ajax_form').submit(function(){
				var dados2 = jQuery( this ).serialize();					
				var opt2 = {
					type: "POST",
					url: "processa2.php",					
					cache: false,
					success: function(){						
						alert( "teste 2" );
					}
				};
				requestRunning = true;
				$.ajax(opt2);				
				return false;				
			});			
		});				
	});
	</script>
</head>
<body>
	<form method="post" action="" id="ajax_form">
		<label><input type="hidden" name="id" value="" /></label>
		<label>Nome: <input type="text" name="nome" value="" /></label>
		<label>Email: <input type="text" name="email" value="" /></label>
		<label>Telefone: <input type="text" name="telefone" value="" /></label>

		<label><input type="submit" name="enviar" value="Enviar" id="enviar" /></label>
		<label><input type="submit" name="enviar" value="Testar" id="testar" /></label>
	</form>
</body>
</html>

Se alguem puder me ajudar

3 Respostas

D

coloca os botões fora do form

S

Os botões fora do form não resolverão o problema, pois ele continua sem saber qual botão foi clicado.

Não é ideal já que o certo é cada botão submit trabalhar para um formulário específico, mas se realmente precisa fazer os dois estarem no mesmo formulário, troque-os por button simples ao invés de submit e declare uma função em cada botão passando o id:

<label><input type="submit" name="enviar" value="Enviar" id="enviar" onclick="javascript:enviaForm(this.id);" /></label>  
<label><input type="submit" name="enviar" value="Testar" id="testar" onclick="javascript:enviaForm(this.id);" /></label>

Depois crie a função:

function enviaForm(idBotao) {
    var form = document.forms[0];
    if (idBotao == 'enviar') {
       form.action = "pagina_enviar.html";
    }
    if (idBotao == 'testar') {
        form.action = "pagina_testar.html";
    }
    form.submit(); // vai enviar para o action modificado nos if's.    
}

Como disse anteriormente, não é o ideal, mas é uma solução viável.

Outra coisa, se você usa ajax, mais um motivo para não utilizar submit, pois a página não precisa ser recarregada correto?

O exemplo que fiz usa javascript puro, mas se usar a mesma lógica, pode colocar diretamente no jQuery, basta apenas mudar os botões.

Espero ter ajudado.

T

Olá amigos,

Através das dicas e com o plugin JqueryForm (http://www.malsup.com/jquery/form/#html), consegui chegar no resultado conforme o link abaixo.

[url]http://www.wlocation.com/testes/[/url]

Meu problema agora é com as div #status, quando o registro inserido com sucesso no banco de dados, é retornado a mensagem de "Reservado" apenas na célula do dia 1/mesa 1.

Via Jquery é ocultado a div=#escrever e exibido a div=#status.

Como eu poderia fazer dezenas de submits cada um com uma div correspondente, ou ontra forma de retorna a mensagem de "reservado" para cada célula?

Pensei em trabalhar com Array ou o método fieldValue, mas não consegui a solução.

Por favor ajude-me.

Desde já agradeço

Abaixo código do link:

Link para download do código-fonte:
[url]https://mega.co.nz/#!XR1TzQjT!4zlB3ezFUcqEj1hQsl89P2JxGak3Gt5cZLDr9VwEIWQ[/url]

Código PHP:
envia.php

[code]<?php

// Informações para conexão
$host = "localhost";
$usuario = "root";
$senha = "";
$banco = "test";

// Realizando conexão e selecioando banco de dados
$conn = mysql_connect($host, $usuario, $senha) or die(mysql_error());
$db = mysql_select_db($banco, $conn) or die(mysql_error()); 
mysql_set_charset('utf8');


// Recuperamos os valores dos campos através do método POST
$id_cliente = $_POST["id_cliente"];
$id_mesa = $_POST["id_mesa"];
$dia = $_POST["dia"];

// Verifica se o nome foi preenchido
if (empty($id_cliente)) {
	echo "Entre com o cliente";
} 

// Verifica se a mensagem foi digitada
elseif (empty($id_mesa)) {
	echo "Entre com a mesa";
} 
// Verifica se a mensagem nao ultrapassa o limite de caracteres
elseif (empty($dia)) {
	echo "Entre com o dia";
} 
// Se não houver nenhum erro
else {
	// Inserimos no banco de dados
	$query = mysql_query("INSERT INTO mesa VALUES ('', '".$id_cliente."', '".$id_mesa."', '".$dia."')");
	
	// Se inserido com sucesso
	if ($query) {
		echo false;
	} 
	
	// Se houver algum erro ao inserir
	else {
		echo "Erro ao inserir o registro";
	}
}
?>

Código HTML/Java Script:
index.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Envio de formulário sem refresh com JQuery/PHP</title>
<style type="text/css">

#status {
	display: none;
}
</style>
<!-- Incluimos a biblioteca do jquery -->
<script src="jquery-1.9.1.min.js"></script> 
<script src="jquery.form.min.js"></script> 

<!-- Criamos as funções necessárias para envio do formulário -->
<script type="text/javascript" language="javascript">

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    $("#status").html("<img src='loader.gif' alt='Enviando' />");
	var options = { 
        target:        '#output2',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse,  // post-submit callback 
 
        // other available options: 
		type: "POST",
		url: "envia.php"
        //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' 
	$('#formulario').ajaxForm(options);
	$('#formulario2').ajaxForm(options);
	$('#formulario3').ajaxForm(options);
	$('#formulario4').ajaxForm(options);

}); 
 
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
	 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    var formElement = jqForm[0]; 
 
    alert('Dados do submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit 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 ajaxSubmit 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('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
     '\n\nThe output div should have already been updated with the responseText.'); 
	 	  
	  $("#status").show();
	  
	  // Exibe mensagem de sucesso
	  $("#status").html("<strong>Reservado</strong>");
	  // Coloca a mensagem no div de mensagens
	  //$("#status").prepend("<strong>"+ nome +"</strong>");

	  //Oculta o form
	  $("#escrever").hide();
}
	
</script>

</head>

<body>

<!-- DIV para retornar mensagens de erro -->
<div id="output2"></div>

<table width="400" border="1">
  <tr>
    <th scope="col">&nbsp;</th>
    <th scope="col">Dia 1</th>
    <th scope="col">Dia 2</th>
  </tr>
  <tr>
    <th scope="row">Mesa 1</th>
      <td>

<!-- DIV para exibir a mesagem de reservado -->
<div id="status"></div>

<!-- Código célula Dia 1 / Mesa 1 - após gravação no BD essa DIV é ocultada -->
<div id="escrever">
<form id="formulario" action="" method="post">
    <input name="id_cliente" id="id_cliente" type="hidden" value="1" />
    <input name="id_mesa" id="id_mesa" type="hidden" value="1"/>
    <input name="dia" id="dia" type="hidden" value="1" />
    <input type="submit"  name="submitButton1" value="Reservar" />
</form>
</div>
    
    </td>
    <td>
    
<!-- DIV para exibir a mesagem de reservado -->
<div id="status"></div>

<!-- Código célula Dia 2 / Mesa 1 - após gravação no BD essa DIV é ocultada -->
<div id="escrever">
<form id="formulario2" action="" method="post">
    <input name="id_cliente" id="id_cliente" type="hidden" value="1" />
    <input name="id_mesa" id="id_mesa" type="hidden" value="1"/>
    <input name="dia" id="dia" type="hidden" value="2" />
    <input type="submit"  name="submitButton1" value="Reservar" />
</form>
</div>    
    
    
    </td>
  </tr>
  <tr>
    <th scope="row">Mesa 2</th>
    <td>
    
<!-- DIV para exibir a mesagem de reservado -->
<div id="status"></div>

<!-- Código célula Dia 1 / Mesa 2 - após gravação no BD essa DIV é ocultada -->
<div id="escrever">
<form id="formulario3" action="" method="post">
    <input name="id_cliente" id="id_cliente" type="hidden" value="1" />
    <input name="id_mesa" id="id_mesa" type="hidden" value="2"/>
    <input name="dia" id="dia" type="hidden" value="1" />
    <input type="submit"  name="submitButton1" value="Reservar" />
</form>
</div>
    
    
    </td>
    <td>
    
<!-- DIV para exibir a mesagem de reservado -->
<div id="status"></div>

<!-- Código célula Dia 2 / Mesa 2 - após gravação no BD essa DIV é ocultada -->
<div id="escrever">
<form id="formulario4" action="" method="post">
    <input name="id_cliente" id="id_cliente" type="hidden" value="1" />
    <input name="id_mesa" id="id_mesa" type="hidden" value="2"/>
    <input name="dia" id="dia" type="hidden" value="2" />
    <input type="submit"  name="submitButton1" value="Reservar" />
</form>
</div>
    
    </td>
  </tr>
</table>

</body>
</html>
Criado 5 de março de 2013
Ultima resposta 15 de abr. de 2014
Respostas 3
Participantes 4