I would start with my code...
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
comment: "required"
},
messages: {
name: "Empty.",
email: "Invalid email.",
comment: "Empty.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
The above code is working fine with the form below, and giving success message out of my process.php fine into div with id results but i have another div before that with id comments which selects and displays the data from the same table where this ajax/jquery form stores the data...I want to refresh that with the latest changes when the form is submitted..have a look at my code first.
<div id="comments">
<h2>Comments</h2>
<?php
$query3 = "SELECT name, c_c, c_date FROM blog_comments WHERE art_id='$id'";
$result3 = #mysql_query($query3);
while($rr=mysql_fetch_array($result3))
{
echo '<div class="comen">';
echo "<h3>";
echo $rr['name'];
echo "</h3>";
echo "<h4>";
echo $rr['c_date'];
echo "</h4>";
echo "<p>";
echo $rr['c_c'];
echo "</p>";
echo '</div>';
}
mysql_close();
?>
</div>
<p>Post your comments. All fields are obligatory.</p>
<div id="results"></div>
<form action="" id="cForm" name="cForm" method="post" class="cform">
<table>
<tr><td><label for="name" id="name_label">Name</label></td><td><input type="text" name="name" id="name" size="30" /></td></tr>
<tr><td><label for="email" id="email_label">Email</label></td><td><input type="text" name="email" id="email" size="30" /></td></tr>
<tr><td><label for="comment" id="comment_label">Comment</label></td><td><textarea name="comment" id="comment" cols="30" rows="5"></textarea></td></tr>
<tr><td><input type="hidden" name="idi" value="<?php echo $id ?>" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Submit" /></td></tr>
</table>
</form>
and my process php looks like this
if (isset($_POST['submit']))
{
include ('databas/conektion.php');
function escape_data ($data)
{
global $con;
if (ini_get('magic_quotes_gpc'))
{
$data = stripslashes($data);
}
return mysql_real_escape_string($data,$con);
}
if (empty($_POST['name']))
{
$n = FALSE;
echo '<p>Invalid name</p>';
}
else
{
$n = escape_data($_POST['name']);
}
if (empty($_POST['email']))
{
$e = FALSE;
echo '<p>Invalid Email</p>';
}
else
{
$e = escape_data($_POST['email']);
}
if (empty($_POST['comment']))
{
$c = FALSE;
echo '<p>Invalid Comments</p>';
}
else
{
$c = escape_data($_POST['comment']);
}
$id = $_POST['idi'];
if($n && $e && $c)
{
$query2 = "INSERT INTO blog_comments (name, c_email, c_c, art_id, c_date) VALUES ('$n', '$e', '$c', '$id', NOW())";
$result2 = #mysql_query($query2);
if($result2)
{
echo '<p>Your comments have been posted successfully.</p>';
}
else
{
echo '<p>System Error</p><p>' . mysql_error() . '</p>';
}
mysql_close();
}
else
{
echo '<p style="color:red">Please try again.</p>';
}
}
?>
what i want to do is refresh div with id comments, once form is submitted.what changes should i make in my code...thanks!!
Create a new file called comments.php (with source code of your comments block)
Initially load comments
$(document).ready(function() { $("#comments_div").load("comments.php"); });
Then when you want to refresh, just call $("#comments_div").load("comments.php");
ie. from your first given code
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
$("#comments_div").load("comments.php");
});
}
EDIT:
If you have an ID in your url, then replace
$("#comments_div").load("comments.php");
with
$.get("comments.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comments_div").html(response);
}
);
Where your_id is the name of GET parameter.
EDIT2:
So how about if you try something like:
$.get("comments.php", {id: <?php echo (0+$_GET['id']); ?>},
function(response) {
$("#comments_div").html(response);
}
);
Thanks bro for your help,,and giving me so much time...my head tags look like this altogether now...
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title; ?></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"> </script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
comment: "required"
},
messages: {
name: "Empty.",
email: "Invalid email.",
comment: "Empty.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
$.get("comment.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comment").html(response);
}
);
});
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function() { $.get("comment.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comment").html(response);
}
); });
</script>
</head>
Related
I have this code from index.php :
<?php
require("../inc/config.php");
$url = $_GET['url'];
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<form method="" action="">
<textarea type="text" class="form-control" id="ketqua" name="ketqua" value="" required="" placeholder="Name|Url" rows="6"></textarea>
<input type="text" class="form-control" id="link" name="link" required="" value="<?php echo $url ?>">
<button type="button" class="btn btn-success" name="insert-data" id="insert-data" onclick="ThemTap()">Add</button>
</form>
<script type="text/javascript">
function ThemTap() {
var ketqua = $("#ketqua").val();
var link = $("#link").val();
$.ajax({
type: "POST",
url: "api.php",
data: {
action: 'ThemTap',
ketqua: ketqua,
link: link
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
This is my api.php .I think my code is missing or missing in this section and I don't know how to solve it:
<?php
include('../inc/config.php');
if($_POST['action'] == 'ThemTap') {
$ketqua=$_POST['ketqua'];
$string = $ketqua;
$HuuNhan = explode('|',$string);
$link=$_POST['link'];
$stmt = $DBcon->prepare("INSERT INTO tap(tap,link,player) VALUES(N'".$HuuNhan[0]."', N'$link',N'".$HuuNhan[1]."')");
mysqli_query($conn,"UPDATE phim SET updatephim = updatephim + 1 WHERE link = '$link'");
if($stmt->execute())
{
if (mysqli_query($conn, $sql)) {
}
$res="<div class='alert alert-success'>Đã thêm tập <b>".$HuuNhan[0]."</b> thành công !</div>";
echo json_encode($res);
}
else {
$error="<div class='alert alert-danger'>Thêm không thành công</div>";
echo json_encode($error);
}
}
?>
I tried running it as follows:
From text area
EP1|Link1
EP2|Link2
EP3|Link3
But it only inserts a row:
EP1|Link
And not insert EP2|Link2 and EP3|Link3
Please correct my source code so I can add many different rows, thank you very much!
I have a code, in a file called service.php which does as follows:
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
// Code to add entry into database
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
And the file to send the data via POST method using AJAX is:
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
The action attribute of the form #addRunner is:
<form action="service.php" id="addRunner" name="addRunner" method="POST">
<!-- Form Elements -->
</form>
Note that the action attribute for the form element is simply service.php instead of service.php?action=addRunner. However, the form still works perfectly, and successfully adds new "runner" information into the database. How does this happen?
Shouldn't the condition ($_POST['action'] == 'addRunner') fail and prevent the code to enter data into the database from running?
For the sake of completeness, the entirity of my code is as below.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>2011 Race Finishers</title>
<link href="styles/my_style.css" rel="stylesheet">
</head>
<body>
<header>
<h2>2011 Race Finishers!</h2>
</header>
<div id="main">
<ul class="idTabs">
<li>Male Finishers</li>
<li>Female Finishers</li>
<li>All Finishers</li>
<li>Add New Finishers</li>
</ul>
<div id="male">
<h4>Male Finishers</h4>
<ul id="finishers_m"></ul>
</div>
<div id="female">
<h4>Female Finishers</h4>
<ul id="finishers_f"></ul>
</div>
<div id="all">
<h4>All Finishers</h4>
<ul id="finishers_all"></ul>
</div>
<div id="new">
<h4>Add New Finishers</h4>
<form action="service.php" id="addRunner" name="addRunner" method="POST">
First Name: <input type="text" name="txtFirstName" id="txtFirstName"> <br>
Last Name: <input type="text" name="txtLastName" id="txtLastName"> <br>
Gender: <select name="ddlGender" id="ddlGender">
<option value="">--Please Select--</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select> <br>
Finish Time:
<input type="text" id="txtMinutes" name="txtMinutes" size="10" maxlength="2">
<input type="text" id="txtSeconds" name="txtSeconds" size="10" maxlength="2">
<br><br>
<button id="btnSave" type="sumbit" name="btnSave">Add Runner</button>
<input type="hidden" id="action" name="action" value="addRunner">
</form>
</div>
</div>
<footer>
<h4>Congratulations to all our finishers!</h4>
<button id="btnStart">Start Page Updates</button>
<button id="btnStop">Stop Page Updates</button>
<br>
<span id="freq"></span><br><br>
Last Updated: <div id="updatedTime"></div>
</footer>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_scripts.js"></script>
<script src="scripts/jquery.idTabs.min.js"></script>
</body>
</html>
My jQuery is:
$(document).ready(function(){
var FREQ = 10000 ;
var repeat = true;
function showFrequency(){
$("#freq").html( "Page refreshes every " + FREQ/1000 + " second(s).");
}
function startAJAXcalls(){
if(repeat){
setTimeout( function() {
getDBRacers();
startAJAXcalls();
},
FREQ
);
}
}
function getXMLRacers(){
$.ajax({
url: "finishers.xml",
cache: false,
dataType: "xml",
success: function(xml){
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$(xml).find("runner").each(function() {
var info = '<li>Name: ' + $(this).find("fname").text() + ' ' + $(this).find("lname").text() + '. Time: ' + $(this).find("time").text() + '</li>';
if( $(this).find("gender").text() == "m" ){
$('#finishers_m').append( info );
}else if ( $(this).find("gender").text() == "f" ){
$('#finishers_f').append( info );
}else{ }
$('#finishers_all').append( info );
});
getTimeAjax();
}
});
}
function getDBRacers()
{
$.getJSON("service.php?action=getRunners", function(json)
{
if(json.runners.length > 0)
{
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$.each(json.runners, function()
{
var info = '<li>Name: ' + this['fname'] + ' ' + this['lname'] + '. Time: ' + this['time'] + '</li>';
if(this['gender'] == 'm')
{
$('#finishers_m').append(info);
}
else if(this['gender'] == 'f')
{
$('#finishers_f').append(info);
}
else {}
$('#finishers_all').append(info);
});
}
});
getTimeAjax();
}
function getTimeAjax(){
var time = "";
$.ajax({
url: "time.php",
cache: false,
success: function(data){
$('#updatedTime').html(data);
}
});
}
$("#btnStop").click(function(){
repeat = false;
$("#freq").html( "Updates paused." );
});
$("#btnStart").click(function(){
repeat = true;
startAJAXcalls();
showFrequency();
});
showFrequency();
getDBRacers();
startAJAXcalls();
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
function clearInputs()
{
$("#addRunner:input").each(function(){
$(this).val('');
});
}
$("#addRunner").submit(function() {
return false;
});
});
And finally the contents of Service.php is:
<?php
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname))
{
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) )
{
fail('Please enter a first and last name.');
}
if( empty($gender) )
{
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result)
{
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
}
else
{
fail('Insert failed.');
}
exit;
}
else if($_GET['action'] == 'getRunners')
{
$query = "SELECT first_name, last_name, gender, finish_time FROM runners ORDER BY finish_time ASC";
$result = db_connection($query);
$runners = array();
while($row = mysqli_fetch_array($result))
{
array_push($runners, array('fname' => $row['first_name'], 'lname' => $row['last_name'], 'gender' => $row['gender'], 'time' => $row['finish_time']));
}
echo json_encode(array("runners" => $runners));
exit;
}
function db_connection($query)
{
$dbc = mysqli_connect('127.0.0.1','runner_db_user','runner_db_password','race_info')
or die('Error connecting to Database');
return mysqli_query($dbc,$query);
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
It will work reason behind this is action is value of name attribute from hidden field. It is not the action of your form tag. If you want to make it fail for testing purpose you should change the value of hidden field to something else in your form and then check again.
This is your hidden field
<input type="hidden" id="action" name="action" value="addRunner">
You can do like this for testing only
<input type="hidden" id="action" name="action" value="addRunners">
It will not satisfy this if condition
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
Hopefully someone can help me here, I am tired of banging my head on the desk. I am not sure why the json response isn't showing up on the div below the form. I can see the response in my firebug debugger(Firefox debugger), but nothing shows up in div.
I've the main register.php that contains the form and javascript and calls another register.php file with the php code that calls the registration function. I can create new account and data files to the database without any problem, but I am unable to get the response back in my div. Please help!
register.php
<body>
<div class="logo"></div>
<div class="form">
<form id="register" method="post">
<input type="text" name="email" id="email" placeholder="Email Address" /><br/><br/>
<input type="text" name="username" id="username" placeholder="Username" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="submit" id="register" value="Register" />
</form>
</div>
<div class="small">
I already have an account<br/>
</div>
<div id="message"></div>
<script type="text/javascript">
$(document).ready(function(){
var myForm = $('#register');
myForm.validate({
errorClass: "errormessage",
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
email: { required: true, email: true, minlength: 3, maxlength: 100 },
username: { required: true, minlength: 3, maxlength: 30 },
password: { required: true, minlength: 3, maxlength: 100 }
},
errorPlacement: function(error, element)
{
var elem = $(element),
corners = ['right center', 'left center'],
flipIt = elem.parents('span.right').length > 0;
if(!error.is(':empty')) {
elem.filter(':not(.valid)').qtip({
overwrite: false,
content: error,
position: {
my: corners[ flipIt ? 0 : 1 ],
at: corners[ flipIt ? 1 : 0 ],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-red'
}
})
.qtip('option', 'content.text', error);
}
else { elem.qtip('destroy'); }
},
success: $.noop,
})
});
$("#register").submit(function(event) {
if($("#register").valid()) {
event.preventDefault();
var $form = $( this ),
mail = $form.find('input[name="email"]').val(),
user = $form.find('input[name="username"]').val(),
pass = $().crypt({method:"sha1",source:$().crypt({method:"sha1",source:$form.find('input[name="password"]').val()})});
$.post("inc/action.php?a=register", {email: mail, username: user, password: pass},
function(data) {
$("#message").html('<p> code: ' + data.error + '</p>');
$("#message").append('<p> message: ' + data.message + '</p>');
}, "json"
);
}
else
{
$("[id^=ui-tooltip-]").effect("pulsate", {times: 3}, 300);
return false;
}
});
</script>
</body>
register.php
<?php
if(isset($_POST['email'])) { $email = $_POST['email']; } else { echo 1; exit(); }
if(isset($_POST['username'])) { $username = $_POST['username']; } else { echo 1; exit(); }
if(isset($_POST['password'])) { $password = $_POST['password']; } else { echo 1; exit(); }
$register = $auth->register($email, $username, $password);
$return = array();
switch($register['code'])
{
case 0:
$return['error'] = 1;
$return['message'] = "You are temporarily locked out of the system. Please try again in 30 minutes.";
break;
case 1:
$return['error'] = 1;
$return['message'] = "Username / Password is invalid";
break;
case 2:
$return['error'] = 1;
$return['message'] = "Email is already in use";
break;
case 3:
$return['error'] = 1;
$return['message'] = "Username is already in use";
break;
case 4:
$return['error'] = 0;
$return['message'] = "Account created ! Activation email sent to " . $register['email'];
break;
default:
$return['error'] = 1;
$return['message'] = "System error encountered";
break;
}
$return = json_encode($return);
echo $return;
Add header('Content-Type: application/json') before returning the json-encoded data.
in json.php
<?php
$data['error']=1;
$data['msg']="error";
header('Content-Type: application/json');
echo json_encode($data);
?>
in index.php
<script type="text/javascript">
$.ajax({
url:'json.php',
success:function(data){
$('body').html(data.msg);
}
});
</script>
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>
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.