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"> </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>