Mysql query by loading table with search button

Asked

Viewed 3,043 times

2

I need some help.

I need to make a Search button, get the parameters of some selects(combobox) and update a table below the filters.

But I don’t quite know how to do this, to press every click on the button.

Follow the code I’ve made:

<?php
require_once("conecta.php"); 
?>
<table>
<tr>
	<td>
	Marca:<select>
		<option>Selecione...</option>
			<?php 
			$query = mysql_query("SELECT * FROM sis_marca");
			while($linha = mysql_fetch_array($query)) { ?>
			<option value="<?php echo $linha['cod_marca'] ?>"><?php echo $linha['desc_marca'] ?></option>
			<?php } ?>
		</select>
	</td>
	<td>
	Modelo:<select>
	<option>Selecione...</option>
			<?php 
			$query = mysql_query("SELECT * FROM sis_modelo");
			while($linha = mysql_fetch_array($query)) { ?>
			<option value="<?php echo $linha['seq_modelo'] ?>"><?php echo $linha['desc_modelo'] ?></option>
			<?php } ?>
		</select>
	</td>
	<td>
	Tipo Modelo:<select>
	<option>Selecione...</option>
			<?php 
			$query = mysql_query("SELECT * FROM sis_tipo_modelo");
			while($linha = mysql_fetch_array($query)) { ?>
			<option value="<?php echo $linha['seq_tipo'] ?>"><?php echo $linha['desc_tipo'] ?></option>
			<?php } ?>
		</select>
	</td>
	<td>
	<input type="submit" value="Buscar" name="g_marca" />
	</td>
</tr>

</table>
<table border="0">
<tr bgcolor="#CCCCCC">
   <td width="300"><b>Marca</b></td>
   <td width="300"><b>Modelo</b></td>
</tr>
<?php
$query = "SELECT * FROM sis_tipo_modelo_oleo";

$resultado = mysql_query($query);
while ($linha = mysql_fetch_array($resultado)) {
	$cod_marca = $linha["cod_marca"];
	$cod_modelo= $linha["cod_modelo"];

?>
<tr>
      <td><? echo $linha['cod_marca']; ?></td>
      <td><? echo $linha['cod_modelo']; ?></td>
</tr>
<?php
}
?>

  • André if you need that when selecting different results within the selects there is a data toggle within the page below the form according to the selection, you will need jQuery and Ajax to order the database.

1 answer

6

So that when you click the button Buscar a database query is carried out which will allow you to obtain new elements to put in the table you must make use of Javascript and the Ajax method to detect the click and trigger a communication with the server:

Example with the jQuery framework:

$('input[name="g_marca"]').click(function(e) {
  e.preventDefault();

  $.ajax({

    type: "POST",
    url: $('#meuFormulario').attr("action"),
    data: $('#meuFormulario').serializeArray(),
    beforeSend: function(xhr, opts) {

      // código antes de comunicar com o servidor
      // util para validar dados, etc...

      // podes chamar xhr.abort(); para cancelar a comunicação
      // com o servidor caso a validação tenha falhado
    },
    success: function(dados) {

      // código após comunicação com o servidor
      // onde recebemos na variavel 'dados' o
      // output que o servidor enviou

      // aqui é onde preparas o novo HTML para
      // atualizar a tua tabela.
    }
  });
});

What is being done:

A click event is attached to your button with the name g_marca:

$('input[name="g_marca"]').click(function(e) { /* ... */ });

We call the method preventDefault() (English) in the click event designated by e to cancel any native behavior associated with it:

e.preventDefault();

We execute an asynchronous HTTP request (Ajax) where we make use of the function $.ajax() (English):

$.ajax({

  // método de comunicação com o servidor 'GET' ou 'POST'
  type: "POST",

  // endereço destino onde está o ficheiro que vai receber a comunicação
  // e devolver os dados que pretendemos 
  url: "http://www.example.com/atualizaTabela.php",

  // código a ser executado antes da comunicação iniciar
  beforeSend: function(xhr, opts) { },

  // código a ser executado após a comunicação ter sido realizada com sucesso
  success: function(dados) { }
});

Considerations:

In order for your HTML to be well built, your elements that make up the form must effectively be within the marking of a form:

<form action="http://www.example.com/atualizaTabela.php" id="meuFormulario">
  <!-- Caixas de seleção, botão de envio entre outros -->
</form>

This way, and as it can be viewed in the sample code at the beginning of the answer, you can without much trouble get the values we want to send to the server and get the address where the target file is:

// Recolher do formulário com o ID 'meuFormulario' o conteúdo do atributo 'action'
url: $('#meuFormulario').attr("action"),

// fazendo uso do método 'serializeArray()' convertemos todos os dados
// escolhidos no formulário numa string pronta a enviar para o servidor
data: $('#meuFormulario').serializeArray(),

Learn more about the method .serializeArray() (English).

Another great advantage of having HTML in its correct form is the fallback for cases where the user has Javascript disabled, where the form with the action defined and the button of submit will allow the page to work normally, being the data sent to the server by the form itself, thus avoiding a breach of usability.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.