Ajax & PHP email with JSON return - php

I have a simple contact form. I got the invalid email and fill all the fields error messages correctly, but I don't get the success message. Hence it's sending the email twice without giving any returning success messages (I just click once, I'm sure about that).
The JS part:
<script language="javascript" type="text/javascript" >
$(function(){
$("#ContactForm").submit(function(){
$("#submitf").value='Sending...';
$.post("send.php", $("#ContactForm").serialize(),
function(data){
if(data.frm_check == 'error'){
$("#message_post").html("<div class='errorMessage'>Error: " + data.msg + "!</div>");
document.ContactForm.submitf.value='Send Again >>';
document.ContactForm.submitf.disabled=false;
} else if(data.frm_check == 'done') {
$("#message_post").html("<div class='successMessage'>Thanks, " + data.msg + "!</div>");
}
}, "json");
return false;
});
});
</script>
The PHP part:
$return_arr = array();
$email = $_POST["email"];
$message= $_POST["message"];
$name= xss_protect(sacarXss($_POST["name"]));
if(!empty($email) && !empty($name) && !empty($message)) {
if(isValidEmail($email)){
$return_arr["frm_check"] = 'done';
$return_arr["msg"] = "Success";
send_mail($email, $name, $message);
}
else{
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Invalid email";
}
} else {
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Fill all the fields.";
}
echo json_encode($return_arr); ?>
The HTML part:
<form method="post" id="ContactForm">
<div class="element">
<input type="text" name="name" class="text" placeholder="name" /><br />
<input type="text" name="email" placeholder="email" class="text" /><br />
<textarea name="message" class="textarea" rows="3" placeholder="message"></textarea><br />
<input type="submit" name="submitf" id="submitf" value="send!"/>
</div>
<div id='message_post'></div>
</form>

I think the form is sent twice to the php script: via the javascript and the submit button of the form. If you change the type of the submit button from 'submit' to 'button', the form will be sent only once.
You must parse the JSON response, so the javascript function becomes:
<script language="javascript" type="text/javascript" >
$(function(){
$("#ContactForm").submit(function(){
$("#submitf").value='Sending...';
$.post("send.php", $("#ContactForm").serialize(),
function(data){
data = jQuery.parseJSON(data);
if(data['frm_check'] == 'error'){
$("#message_post").html("<div class='errorMessage'>Error: " + data['msg'] + "!</div>");
document.ContactForm.submitf.value='Send Again >>';
document.ContactForm.submitf.disabled=false;
} else if(data['frm_check'] == 'done') {
$("#message_post").html("<div class='successMessage'>Thanks, " + data['msg'] + "!</div>");
}
}, "json");
return false;
});
});
</script>

Related

How do i stop the form validation code from repeating when i click the submit button (php ajax jquery html)

Hey all i'm new to working with ajax but i am trying to make some form validation and its going well except for this code repeating itself.
This is what happens after clicking the submit button twice... and if i keep pressing submit it keeps repeating. I only need it to show once no matter how many times the submit button is pressed.
Much appreciated to anyone who could give me a hint on how to stop this code repeating!! Thanks!
The forms action calls this php file:
$errors = [];
$data = [];
// change the $error message for each field here
if (empty($_POST['name'])) {
$errors['name'] = '<div class="my-3 alert alert-danger";>Please enter a valid name.</div>';
} else if (!empty($_POST['name'])) {
$errors['name'] = '<div class="my-3 alert alert-success";>Name Entered.</div>';
}
if (empty($_POST['email'])) {
$errors['email'] = '<p class="my-3 alert alert-danger";>Please enter a valid email address.</p>';
} else if (!empty($_POST['email'])) {
$errors['email'] = '';
}
if (empty($_POST['comment'])) {
$errors['comment'] = '<p class="my-3 alert alert-danger";>Please leave a comment.</p>';
} else if (!empty($_POST['comment'])) {
$errors['comment'] = '';
}
// if the fields are not empty then return successful
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Your Request Has Been Successful! <a class="text-success" href="./">Click here to continue.</a>';
}
echo json_encode($data);
I also have this form.js file linked:
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
comment: $("#comment").val(),
};
$.ajax({
type: "POST",
url: "./php/process.php",
data: formData,
dataType: "json",
encode: true,
})
.done(function (data) {
console.log(data);
if (!data.success) {
if (data.errors.name) {
$("#name-group").addClass("has-error");
$("#name-group").append(
'<div class="help-block">' + data.errors.name + "</div>"
);
}
if (data.errors.email) {
$("#email-group").addClass("has-error");
$("#email-group").append(
'<div class="help-block">' + data.errors.email + "</div>"
);
}
if (data.errors.comment) {
$("#comment-group").addClass("has-error");
$("#comment-group").append(
'<div class="help-block">' + data.errors.comment + "</div>"
);
}
} else {
$("form").html(
'<div class="alert alert-success">' + data.message + "</div>"
);
}
})
.fail(function (data) {
$("form").html(
'<div class="alert alert-danger">Could not reach server, please try again <a href="./test-form" >here</a>.</div>'
);
});
event.preventDefault();
});
});
And finally the form itself:
<form action="./php/process.php" method="POST">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name"
onchange="myFunction()" />
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email"
placeholder="email#example.com" onchange="myFunction()" />
</div>
<div id="comment-group" class="form-group">
<label for="comment">Leave a comment:</label>
<input type="text" class="form-control" id="comment" name="comment"
placeholder="Leave a comment" onchange="myFunction()" />
</div>
<button type="submit" class="btn btn-success">
Submit
</button>
</form>

Receiving success response but the button still disabled using ajax

I am checking email id is available or not in the database using ajax which is working.I have one submit button and that is disabled on page load.I have to enable that button when the user enters the right email address which is available on the database. If email is available in the database the button will enable otherwise button will be disabled.There is some issue in if condition. I tried button still the same issue. Would you help me in this?
$("input[type='submit']").removeAttr("disabled");
$("input[type='submit']").prop('disabled', false);
If I used CSS for button then disable is not working.
Html
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" >
Ajax
$(document).ready(function()
{
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 1) {
$('input[type="submit"]').attr('disabled' , false);
}
else{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr('disabled', true);
}
},
});
});
});
//Disable the button on page load
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
}
Try this-
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "ok") {
$(elem).attr('disabled' , false); //here pass elem
}
else{
$("#email-validation-error").html('Email not available');
$(elem).attr('disabled', true); //here pass elem
}
},
});
});
});
Process.php
include('db/connection.php');
if(isset($_POST['email'])){
$email=$_POST['email'];
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record == 0) {
echo "ok";
}
}
You should check and verify your response:
Process.php
if ($search_record == 0) {
echo "Email does not exist, please sign up to use our services";
}
else{
echo "success";
}
Ajax
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
html
<input id="submitYesNo" type="submit" name="next" value="submit" >
Try This Code .
Hope it will work properly
success:function(data)
{
if (data == 1)
{
$('input[type="submit"]').removeAttr("disabled", "disabled");
}
else
{
$("#email-validation-error").html(data);
$('input[type="submit"]').attr("disabled", "disabled");
}
Finally, I found my answer with the help of Mr.Ahmed Ginani
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form >
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="id" type="submit" name="next" value="submit" disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$(elem).attr('disabled', true);
$("input[name='email']").bind('change',function() // Changes from key press to change and bind
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == 'success') { // getting success name from process.php page
$("#id").attr('disabled' , false);
$("#email-validation-error").html(''); //Change here for hiding the error message
}
else{
$("#email-validation-error").html(data);
$('#id').attr('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
Process.php
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}

stop form from submitting (tried e.preventDefault() after $.post but it stops form from submitting

I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})

How to add AJAX Submit to PHP validation and return message?

I've been working my way up on validating a form and got the JS and PHP validation to work but I am still having a hard time adding ajax(with or without JQUERY) to submit to the php file and return a success message.
My form with CSS and JS validation:
<html>
<head>
<style type="text/css">
#nameerror {
color:red;
}
#emailerror{
color:red;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
var email = document.forms['form']['email'].value;
var atpos = email.indexOf('#');
var dotpos = email.lastIndexOf('.');
var name = document.forms['form']['name'].value;
if (name == null || name == ""){
document.getElementById('nameerror').innerHTML="Please enter your name";
return false;
} else if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
document.getElementById('emailerror').innerHTML="Please enter a valid email";
return false;
} else {
}
}
</script>
</head>
<body>
<div>Sign Up</div>
<form name="form" action="form_validation.php" id="form" onsubmit="return Validate();" method = 'post'>
<label>Name:</label><br/>
<input id='name' type="text" name='name' /><br/>
<span id="nameerror"></span><br/>
<label>Email:</label><br/>
<input type='text' name='email' id = 'email'/> <br/>
<span id= "emailerror"></span><br/>
<label>Comments:</label><br/>
<textarea name='comments' id ='comments'></textarea><br/>
<span id="comerror"></span>
<input type="submit" name="submit" value="Submit"/>
<span id="success" style="display:none">Your message has been sent successfully.</span>
</form>
</body>
</html>
And this is form_validation.php:
<?php
if(isset($_POST['submit'])){
if($_POST['name']){
$name = $_POST['name'];
}
if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
echo "Name can only contain letters.";
return false;
} else {
echo "Name accepted";
}
if($_POST['email']){
$email = $_POST['email'];
}
$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if(!preg_match($pattern, $email)){
echo "Please enter a valid email address.";
return false;
} else {
echo "Email Valid";
}
if($_POST['comments']){
$comments = $_POST['comments'];
}
if (strlen($comments) > 100){
echo "please enter less than 100 characters.";
return false;
}
}
?>
thanks for the help!
$('form').on('submit',function() {
$.ajax({
url: 'form_validation.php',
data: $(this).serialize(),
type: 'POST'
}).done(function(data){
// you can append a success message to your document here
});
});

Php response displays in browser instead of firing the ajax callback

I've spent some time looking on SO for an answer to this and have found some related issues, but nothing quite like mine...as usual....
I've got a fairly simple php/jquery ajax registration page that is working right up until the ajax callback. What I mean is the form data is passing to php and inserting into the db but when the php response is supposed to come back all that happens is the response displays in the browser. I've followed the logs, checked fiddler, re-written the code with/without json, and anothing seems to change. The odd thing is I have another form on a different page that is set up exactly the same way and everything works there perfectly. The only difference I can find between the two pages is the Request Headers of the php file. The one that works accepts json and the one the other one doesn't, but I have no idea if that means anything . . . I'm kind of grabbing for anything at this point.
So, without further delay, here is my code. Any thoughts/input are greatly appreciated. Thank you!
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen and (max-device-width: 480px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" media="screen and (min-width: 481px)" href="IEjoin.css" />
<![endif]-->
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="register.js" type="text/javascript"></script>
<script src="jquery.placeholder.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<div id="logo">
</div>
<div id="headline">
<h1>Create your account</h1>
</div>
<div id="container">
<form id="register" action="form.php" method="post">
<ul>
<li id="first_name">
<input name="fname" type="text" value="" id="fname" placeholder="First Name" maxlength="30">
<div class="error"></div>
</li>
<li id="last_name">
<input name="lname" type="text" value="" id="lname" placeholder="Last Name" maxlength="30">
<div class="error"></div>
</li>
<li id="email_address">
<input name="email" type="text" value="" id="email" placeholder="Email Address" maxlength="60">
<div class="error"></div>
</li>
<li id="uname">
<input name="username" type="text" value="" id="username" placeholder="Username" maxlength="15">
<div class="error"></div>
</li>
<li id="pword">
<input name="password" type="password" value="" id="password" placeholder="Password">
<div class="error"></div>
</li>
<li id="gender_select">
<select id="gender" name="gender">
<option value="" selected="selected">Select your gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="unspecified">Unspecified</option>
</select>
</li>
<li id="submit_button">
<button id="register_button" class="register_button_disabled">Create Account</button>
</li>
</ul>
</form>
<script> $('input[placeholder]').placeholder();</script>
</div>
</div>
</body>
$(document).ready(function() {
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email);
}
function submitButton() {
if (($("#first_name").hasClass("good")) && ($("#email_address").hasClass("good")) && ($("#uname").hasClass("good")) && ($("#pword").hasClass("good")) ){
$("#register_button").removeAttr("disabled");
$("#register_button").removeClass("register_button_disabled").addClass("register_button");
} else {
$("#register_button").attr("disabled", "disabled");
$("#register_button").removeClass("register_button").addClass("register_button_disabled");
}
}
$("body").mousedown(submitButton);
$("body").keyup(submitButton);
$("body").hover(submitButton);
$("body").mouseover(submitButton);
$("#fname").keydown(function(){
$("#first_name").removeClass("required");
$("#first_name div").html("");
});
$("#fname").bind ("keyup mousedown",function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("wait");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#fname").blur(function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#email").keydown(function(){
$("#email_address").removeClass("required");
$("#email_address div").html("");
});
$("#email").bind ("keyup mousedown",function(){
var email = this.value;
var emailLength = email.length;
if (emailLength<=4){
$("#email_address").removeClass("good").addClass("wait");
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#email").blur(function(){
var email = this.value;
var emailLength = email.length;
if ((emailLength<=4) || (!validateEmail(this.value))) {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (emailLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "Check.php",
data: "email="+email,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");}
else {
$("#email_address").removeClass("wait").addClass("good");
}
}
});
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#username").keydown(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("wait");
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#username").bind ("keyup mousedown",function(){
$("#uname").removeClass("required");
$("#uname div").html("");
});
$("#username").blur(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (unLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "check.php",
data: "username="+un,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
$("#uname").removeClass("wait").addClass("good");
}
}
});
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#password").keydown(function(){
var pw = this.value;
var pwLength = pw.length;
if(pwLength<=5){
$("#pword").removeClass("good").addClass("wait");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#password").bind ("keyup mousedown",function(){
$("#pword").removeClass("required");
$("#pword div").html("");
});
$("#password").blur(function(){
var pw = this.value;
var pwLength = pw.length;
if(pw===""){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please enter a password");
}
if(pwLength<=5){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please use at least 6 characters");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: "form.php",
data: $('#register').serialize(),
success: function(data) {
if (data === "fname") {
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else if (data === "email") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (data === "email2") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");
} else if (data === "username") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (data === "username2") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
window.location.href = "http://site.com";
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
return false;
});
});
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$gender = mysql_real_escape_string($_POST['gender']);
//validate inputs
$emailpull = "SELECT email FROM $tbl_name WHERE email='$email'";
$emailresult=mysql_query($emailpull);
$emailnum=mysql_num_rows($emailresult);
$emailReg = "/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/";
$unpull = "SELECT username FROM $tbl_name WHERE username='$username'";
$unresult=mysql_query($unpull);
$unnum=mysql_num_rows($unresult);
if ($fname == "") {
$response = "fname";
} elseif ($email == "") {
$response = 'email';
} elseif (!preg_match($emailReg, $email)) {
$response = 'email';
} elseif ($emailnum > 0) {
$response = 'email2';
} elseif (strlen($username)<3) {
$response = 'username';
} elseif ($unnum > 0) {
$response = 'username2';
} elseif (strlen($password)<6) {
$response = 'password';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(fname,lname,email,username,password,gender)VALUES ('$fname','$lname','$email','$username','$password','$gender')";
}
$result=mysql_query($sql);
if($result)
$response = "success";
// send message back
echo $response;
?>
<?php
// close connection
mysql_close();
?>
The click handler for #button has this line which may be the culprit:
window.location.href = "http://crushonit.com";
This will redirect to that page when the form has no validation errors.

Categories