AJAX form tutorial using jQuery and PHP

Started by PF2G, December 29, 2011, 10:55:20 AM

PF2G

Hi,
I have a example of a validation but can't join the validation codes to my registration form.

HERE'S THE EXAMPLES:
ajax_submit.js

/*
Created By: Aaron Tennyson @ http://aarontennyson.com
Date: January 13. 2011
Copyright 2011 Aaron Tennyson
*/

$(document).ready(function() {

$('form #response').hide();

$('#submit').click(function(e) {

// prevent forms default action until
// error check has been performed
e.preventDefault();

// grab form field values
var valid = '';
var required = ' is required.';
var name = $('form #name').val();
var email = $('form #email').val();
var message = $('form #message').val();
var honeypot = $('form #honeypot').val();
var humancheck = $('form #humancheck').val();

// perform error checking
if (name = '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}

if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email' + required +'</p>';  
}

if (message = '' || message.length <= 5) {
valid += '<p>A message' + required + '</p>';
}

if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}

if (humancheck != '') {
valid += '<p>A human user' + required + '</p>';
}

// let the user know if there are erros with the form
if (valid != '') {

$('form #response').removeClass().addClass('error')
.html('<strong>Please correct the errors below.</strong>' +valid).fadeIn('fast');
}
// let the user know something is happening behind the scenes
// serialize the form data and send to our ajax function
else {

$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');

var formData = $('form').serialize();
submitForm(formData);
}

});
});

// make our ajax request to the server
function submitForm(formData) {

$.ajax({
type: 'POST',
url: 'feedback.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
success: function(data) {

$('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).fadeIn('fast');

if ($('form #response').hasClass('success')) {

setTimeout("$('form #response').fadeOut('fast')", 5000);
}

},
error: function(XMLHttpRequest, textStatus, errorThrown) {

$('form #response').removeClass().addClass('error')
.html('<p>There was an<strong> ' + errorThrown +
  '</strong> error due to a<strong> ' + textStatus +
  '</strong> condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {

$('form')[0].reset();
}
});
};



feedback.php

<?php 
sleep
(2);
//Sanitize incoming data and store in variable
$name trim(stripslashes(htmlspecialchars($_POST['name'])));   
$email trim(stripslashes(htmlspecialchars($_POST['email'])));
$message trim(stripslashes(htmlspecialchars($_POST['message'])));     
$humancheck $_POST['humancheck'];
$honeypot $_POST['honeypot'];

if (
$honeypot == 'http://' && empty($humancheck)) {

//Validate data and return success or error message
$error_message '';
$reg_exp "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";

if (!preg_match($reg_exp$email)) {
    
$error_message .= "<p>A valid email address is required.</p>";    
}
if (empty($name)) {
   
    $error_message .= "<p>Please provide your name.</p>";    
}
if (empty($message)) {

$error_message .= "<p>A message is required.</p>";
}
if (!empty($error_message)) {
$return['error'] = true;
$return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;
echo json_encode($return);
exit();
} else {
  
$return['error'] = false;
$return['msg'] = "<p>Thanks for your feedback " .$name .".</p>"
echo json_encode($return);
  }
} else {

$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}

?>





index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX form tutorial using jQuery and PHP</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="ajax_submit.js"></script>
</head>

<body>

<div id="wrapper">
   
        <h1>Give us your feedback</h1>
       
      <div id="inner-wrapper">
         
<form id="feedback" action="feedback.php" enctype="multipart/form-data" method="post">
         
          <div id="response"><!--This will hold our error messages and the response from the server. --></div>           
           
                <div class="inputs">
                  <label>Name&nbsp;&nbsp;&nbsp;</label>         
                  <input name="name" type="text" class="required" id="name" size="30" />           
                </div>         
           
                <div class="inputs">
                  <label>Email&nbsp;&nbsp;&nbsp;</label>           
                  <input name="email" type="text" class="required" id="email" size="30" />           
               </div>         
           
                <div class="inputs">
                  <label>Message</label>         
                  <textarea name="message" cols="25" rows="" class="required" id="message"></textarea>         
                </div>                       
               
                <div class="button">
                  <input type="submit" name="submit" id="submit" value="Submit" />
                </div>
               
                <div class="inputs">
                    <input type="hidden" name="honeypot" id="honeypot" value="http://" />           
                    <input type="hidden" name="humancheck" id="humancheck" class="clear" value="" />
                </div>
        </form>
       
      </div><!-- End inner-wrapper -->
               
</div><!-- End wrapper -->

</body>
</html>



styles.css

@charset "utf-8";
body, html {
font-family: Trebuchet MS, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
}
div#wrapper {
height: auto;
width: 500px;
margin-top: 50px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;
border: 2px dotted #999;
background-color: #eee;
}
div#wrapper h1 {
margin-left: 20px;
padding-bottom: 7px;
width: 460px;
color: #666;
border-bottom-width: 2px;
border-bottom-style: inset;
border-bottom-color: #fff;
}
div#wrapper div#inner-wrapper {
padding: 20px;
}
div#wrapper div#inner-wrapper form#feedback div.inputs {
padding: 10px;
color: #666;
}
div#wrapper div#inner-wrapper form#feedback div.inputs textarea#message {
height: 100px;
}
div#wrapper div#inner-wrapper form#feedback div.button {
padding: 10px;
width: 60px;
margin: 15px auto;
}
div#wrapper div#inner-wrapper form#feedback div#response {
color: #333;
border: 1px solid #404040;
width: 360px;
margin: 0 auto 20px auto;
height: auto;
padding: 10px 10px 10px 70px;
min-height: 45px;
}
div#wrapper div#inner-wrapper form#feedback div#response p {
margin: 0;
padding: 0;
}
.clear {
clear: both;
}
.error {
background: #FF9F9F url(error.png) no-repeat 5px 10px;
}
.success {
background: #B8F5B1 url(icon_ok.png) no-repeat 5px 10px;
}
.processing {
background: #DED5AB url(ajax-loader.gif) no-repeat 5px 10px;
}



HERE IS MY REGISTRATION FORM:

    <?PHP
     
    include 'topo.php';
     
    ?>
     
     
    <!-- content -->
     
    <div class="indent">
     
    <h2> Inscrição </h2>
     
     
    <form action="envia.php" method="post" onsubmit="return validar()" >
    <fieldset>
    <legend> ALUNO </legend>
     
    <br/>
    <div class="field"><label>Username*: </label><input type="text" size="30" name = "username"/></div>
    <br/>
    <div class="field"><label>Password*: </label><input type="password" size="25" name = "pass"/></div>
    <br/>
    <div class="field"><label>Confirma Password*: </label><input type="password" size="25" name = "conf_pass"/></div>
    <br/>
    <div class="field"><label>Nome*: </label><input type="text" size="40" name = "nome"/></div>
    <br/>
    <div class="field"><label>Data de Nascimento: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="3" maxlength="2" name = "dia"/> / <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="3" maxlength="2" name = "mes"/> / <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="5" maxlength="4" name = "ano"/> (DD/MM/AAAA)</div>
    <br/>
    <div class="field"><label>Morada: </label><input type="text" onkeypress="return onlyNumbers();" size="39" name = "morada"/></div>
    <br/>
    <div class="field"><label>Código Postal: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="5" maxlength="4" name = "cp1"/> - <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="4" maxlength="3" name = "cp2"/></div>
    <br/>
    <div class="field"><label>Telemóvel*: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="10" maxlength="9" name = "tele"/></div>
    <br/>
    Curso*: <select name="curso">
    <option value = 1> Piano </option>
    <option value = 2> Orgão </option>
    <option value = 3> Guitarra Elétrica </option>
    <option value = 4> Guitarra Acústica </option>
    <option value = 5 Violino </option>
    <option value = 6> Canto </option>
    <option value = 7> Bateria </option>
    <option value = 8> Saxofone </option>
    <option value = 9> Flauta </option>
    <option value = 10> Baixo </option>
    <option value = 11> Violoncelo </option>
    </select>
    <br/>
    <br/>
    <div class="field"><label>E-Mail*: </label><input type="text" value="" name = "email" size = "25"/></div>
    <br/>
    Observações:
    <br/>
    <textarea cols="30" rows="7" name="obs"></textarea>
    </fieldset>
    <br/>
    <fieldset>
    <legend> ENCARREGADO DE EDUCAÇÃO </legend>
     
    <br/>
    <div class="field"><label>Nome*: </label><input type="text" size="40" name = "nome_ee"/></div>
    <br/>
    <div class="field"><label>Morada: </label><input type="text" size="39" name = "morada_ee"/></div>
    <br/>
    <div class="field"><label>Código Postal: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="5" maxlength="4" name = "cp1_ee"/> - <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="4" maxlength="3" name = "cp2_ee"/></div>
    <br/>
    <div class="field">Telemóvel*: </label><input id="txtChar" onkeypress="return isNumberKey(event)" type="text" size="10" maxlength="9" name = "tele_ee"/></div>
    <br/>
    <div class="field"><label>E-Mail*: </label><input type="text" value="" name = "email_ee" size = "25"/></div>
     
    </fieldset>
    <br/>
    * Campos Obrigatórios
    <br/>
    <input type="submit" value="Enviar">
    <input type="Reset" value="Apagar">
     
    </form>
     
    </div>
    </div>
     
     
    <?PHP
     
    include 'rodape.php';
     
    ?>


Can someone help me, please? I need this ASAP.

Thank you,
PF2G