Enviando dados de um formulário usando jQuery

Posted on Fevereiro 7, 2008. Filed under: jQuery | Tags: |

JQuery é um framework de Javascript na minha opinião não é difícil apreender. Este exemplo é para fazer uma inserção usando ajax porém, usando jQuery. Vamos a um exemplo simples.

exemplo1.js
$(document).ready(function(){
$forms = $('form');
$('#cadastro').hide();
$('a').bind('click', function(){
switch(this.id){
case 'c':
$('#cadastro').show();
return false;
break;
}
})
$forms.bind('submit', function(){
var $button = $('button',this).attr('disabled',true);
var params = $(this.elements).serialize();
var self = this;
$.ajax({
type: 'POST',
url: this.action,
data: params,
beforeSend: function(){
$('#loading').show();
$('#loading').html("Carregando...");
},
success: function(txt){
$button.attr('disabled',false);
$('#loading').html(txt);
self.reset();
},
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;
}

index php

form.jpg

insert 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("", "", "");
mysql_select_db("");
$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!";

SQL

CREATE TABLE `cadastro` (
`id` int(10) unsigned NOT NULL auto_increment,
`nome` varchar(30) NOT NULL,
`telefone` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Espero que o exemplo acima ajude.

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

Liked it here?
Why not try sites on the blogroll...