O jQuery é um framework de Javascript na minha opinião de fácil apreendizado.
Este artigo é composto por um exemplo que aboradará a inserção de dados usando jQuery e AJAX em um formulário simples.
Arquivo exemplo1.js:
/**
$(): utilizado em todas as funções que devem ser referenciadas a jQuery
document: expressão que indica o documento HTML
ready(): associado a leitura do documento enquanto está sendo carregado
*/
$(document).ready(function(){
// Crio uma variável chamada $forms que pega o valor da tag form
$forms = $('form');
// hide(): esconde a div cadastro enquanto carrega o ready()
$('#cadastro').hide();
/**
bind(): é manipulador de evento exemplo submit, click e/ou double click
a: é a tag <a href>
*/
$('a').bind('click', function(){
switch(this.id){
case 'c':
$('#cadastro').show(); // show(): mostra div que está oculta (hide()).
return false;
break;
}
})
$forms.bind('submit', function(){
/**
Crio a variável $button
attr(): set a propriedade de um atributo, nesse exemplo foi desativado o botão com a tag button
*/
var $button = $('button',this).attr('disabled',true);
/**
Criada a variável params
serialize(): pega os dados inseridos no formulário
*/
var params = $(this.elements).serialize();
var self = this;
$.ajax({
// Usando metodo Post
type: 'POST',
// this.action pega o script para onde vai ser enviado os dados
url: this.action,
// os dados que pegamos com a função serialize()
data: params,
// Antes de enviar
beforeSend: function(){
// mostro a div loading
$('#loading').show();
// html(): equivalente ao innerHTML
$('#loading').html("Carregando...");
},
success: function(txt){
// Ativo o botão usando a função attr()
$button.attr('disabled',false);
// Escrevo a mensagem
$('#loading').html(txt);
// Limpo o formulário
self.reset();
},
// Se acontecer algum erro é executada essa função
error: function(txt){
$('#loading').html(txt);
}
})
return false;
});
});
CSS:
body{
font: 12px tahoma,verdana;
margin:0;padding:0;
}
#loading{
display: none;
text-align: center;
}
a,a:active,a:hover {
text-decoration:none;
color:#000;
outline:none;
}
ul {
margin-left:5px;
}
li {
list-style:none;
}
li a {
float: left;
display:block;
background:#f1f1f1;
width:50px;
padding:3px;
text-align:center;
margin-right:1px;
border:1px solid #555;
}
li a:hover {
display:block;
background:#f0f0f0;
}
#main{
height: 100%;
border:none;
}
#top {
height: 50px;
}
#middle{
margin-top:5px;
}
fieldset {
padding:8px;
border:1px solid #999;
}
button {
background:#ccc;
padding:0.5px;
}
.border {
border: 1px solid black;
}
Arquivo index.php:
<html>
<head>
<meta http-equiv="Content-Language" content="pt-br" />
<meta name="GENERATOR" content="PHPEclipse 1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>jQuery</title>
<script language="JavaScript" type="text/javascript" src="jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="exemplo1.js"></script>
</head>
<body>
<div id="main">
<div id="loading"></div>
<div id="top">
<ul>
<li><a href="" id="c">Cadastro</a></li>
</ul>
</div> <!-- top -->
<div id="middle">
<div id="cadastro">
<form action="insert.php">
<fieldset>
<legend>Cadastro usando jQuery</legend>
<label>Nome</label><br/>
<input type="text" name="nome" size="31" maxlength="30" class="border"/><br />
<label>Telefone</label><br/>
<input type="text" name="telefone" size="31" maxlength="11" class="border" /><br/>
<label>E-mail</label><br/>
<input type="text" name="email" size="31" maxlength="100" class="border" /><br/>
<button>Cadastrar</button>
</fieldset>
</form>
</div> <!-- cadastro -->
</div> <!-- middle -->
</div> <!-- main -->
</body>
</html>
Arquivo insert.php:
<?php
$nome = strip_tags(trim($_POST['nome']));
$telefone = strip_tags(trim($_POST['telefone']));
$email = strip_tags(trim($_POST['email']));
if(empty($nome) || empty($telefone) || empty($email)){
echo"Você deve preencher todos os campos!";
die();
}
$conn = mysql_connect("SERVIDOR", "USUÁRIO", "SENHA");
mysql_select_db("BANCO");
$sql = "INSERT INTO cadastro (nome, telefone, email) VALUES ('".$nome."', '".$telefone."', '".$email."')" or die(mysql_error());
mysql_query($sql);
mysql_close($conn);
echo"Cadastro realizado com sucesso!";
?>
Espero que o exemplo acima ajude e que incentive o uso da jQuery.