I am using jquery Validation Plugin. I have an email field. If the email is in use, I want the validation plugin to give an error with a link to the client's page.
IE: if I input the email john#bobo.com and he is client #312 with the name John Mark, I want my error to be:
John Mark is using that email.
Preferably I would like to have my external file just echo the entire error and have the jQuery Validation plugin to display that full error. If not, I would like to have both the client name and client id to be returned and then be able to output the error message with a link.
jQuery Code:
$().ready(function() {
// Validate the form
$('#sign-up_area').validate({
rules: {
firstName: "required",
lastName: "required",
email_address: {
email: true,
remote: {
url: "includes/databasecheck.php",
type: "post",
success: function(html){
$("#email").html(html);
}
}
}
},
messages: {
firstName: "First Name Required",
lastName: "Last Name Required",
email_address: {
email: "Email address need to be valid.",
//remote: jQuery.format("{0} is taken")
},
}
});
});
Form:
<form action="#" method="post" id="sign-up_area">
<h2 id="reference" name="reference" class="heading-reference">Client</h2>
<fieldset>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" value="">
</fieldset>
<fieldset>
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" value="">
</fieldset>
<fieldset>
<label for="email_address">Email:</label>
<input type="text" name="email_address" id="email_address" value="">
<div id="email" class="error"></div>
</fieldset>
<fieldset class="form-actions">
<input type="submit" value="Submit">
</fieldset></form>
databasecheck.php
<?php
include_once("config.php"); // database connection
if(isset($_POST['email_address'])) {
$stmt = $mysqli->prepare("SELECT client_id, CONCAT(firstName, ' ', lastName) AS whole_name FROM client WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $_POST['email_address']);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($client_id, $whole_name);
$stmt->fetch();
echo ''.$whole_name.' is using that email.';
}
?>
As per the documentation for the Remote Method, the error message can just be whatever you return from your server.
The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.
As long as you construct the custom error message on the server as valid JSON, your code is fine with the message for remote removed...
rules: {
firstName: "required",
lastName: "required",
email_address: {
email: true,
remote: {
url: "includes/databasecheck.php",
type: "post",
success: function(html){
$("#email").html(html);
}
}
}
},
messages: {
firstName: "First Name Required",
lastName: "Last Name Required",
email_address: {
email: "Email address need to be valid."
// The remote error message is coming from the server automatically
// remote: jQuery.format("{0} is taken") // <- REMOVE
},
}
Try this PHP:
if(isset($_POST['email_address'])) {
$stmt = $mysqli->prepare("SELECT client_id, CONCAT(firstName, ' ', lastName) AS whole_name FROM client WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $_POST['email_address']);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($client_id, $whole_name);
$stmt->fetch();
$response = ''.$whole_name.' is using that email.';
echo json_encode($response); // failed validation- show the message
} else {
echo "true"; // passed validation- no message
}
See: http://php.net/manual/en/function.json-encode.php
Related
I'm trying to config a contact form based on php/ajax to a website, but I can't manage to add a "success" message after the form is submitted. I receive the email correctly if I keep the "action" parameter to the php file inside form tag, but the page gets redirected to the blank php page. However, if I remove the link, the email is not sent.
I've tried in the past hours many of the suggestions I found online, but I can't manage to make it work properly. Any guesses?
Thanks
HTML
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
</div>
PHP
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "abcde#gmail.com";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Your website
";
$referer = $_SERVER['HTTP_REFERER'];
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "includes/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = `enter code here`"From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
?>
JS
$(document).ready(function () {
$("#contact-form").validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true,
maxlength: 8000
}
},
messages: { // custom messages
fullname: {
required: "Por favor, insira seu nome"
},
email: {
required: "Por favor, insira seu email"
},
message: {
required: "Por favor, insira sua mensagem",
maxlength: jQuery.format("The maxlength for message is {0} !")
},
},
submitHandler: function(form) {
$form = $(form);
$container = $form.parent();
w = $form.outerWidth();
h = $form.outerHeight();
$form.hide();
$('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
success: function (data) {
$("#mail-status").html(data);
},
error:function (){}
});
return false;
}
});
});
Where is the "mail-status" id in html? You can replace "mail-status" with "errors".
The issue is there is no "mail-status" id in a page, so it is not displaying response on that div.
Define "mail-status" on html or just replace "mail-status" with "errors", as your html contains .
Put the <div id="errors"></div> outside the form element. When you are hiding the form the <div id="errors"></div> also gets hidden hence you cannot see anything.
<form id="contact-form" method="POST" action="header.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id="errors"></div>
Also in the php file you need to echo $message; so that it should be available in the ajax data param.
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
echo $message;
Perhaps this might help you:
<div id="mail-status"></div>
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">
First, add this element to the html :
<div id="mail-status"></div>
Then add preventDefault() to the js to prevent the form from submitting :
<script>
$(document).ready(function () {
$("#contact-form").submit(function(e) {
e.preventDefault(); // added preventDefault()
}).validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true,
maxlength: 8000
}
},
messages: { // custom messages
fullname: {
required: "Por favor, insira seu nome"
},
email: {
required: "Por favor, insira seu email"
},
message: {
required: "Por favor, insira sua mensagem",
maxlength: jQuery.format("The maxlength for message is {0} !")
},
},
submitHandler: function (form) {
$form = $(form);
$container = $form.parent();
w = $form.outerWidth();
h = $form.outerHeight();
$('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
success: function (data) {
$("#mail-status").html(data);
},
error: function () {}
});
$form.hide(); // moved below ajax call
return false;
}
});
});
</script>
Then don't forget to add echo statement to the php :
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
echo $message;
Perhaps the way you handle the submit is causing the page to redirect?
Change your button type submit to a button. See below,
<input type="button" name="submit" value="Submit" id="submit" />
Then, target the button click for the form submission, like this,
$(document).ready(function () {
$('#submit').click(function(){
//do you logic here
});
});
When changing the button type to be a button, you don't need to worry about preventDefault() for submission, because submission only happens through through Ajax / JS.
Hope this helps.
Cheers
Hi I'm creating a form that contains username password etc.. and I used jquery to validate the form and I want to check that the username is already present in the mysql database. if it is present then the form should not be submitted.
Here is my code so far:
<form id="register" name="register" action="somewhere.php" method="post" >
<label for ="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username" autocomplete="off" placeholder="Enter Username"> <br>
<div class="username_avail_result" id="username_avail_result"></div><br>
<label for ="Password"> Password </label><br>
<input type="password" class="register-control" id="password" name="password" placeholder="Enter Password" ><br><br>
<label for ="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm_Password" name="Confirm_Password" placeholder="Confirm Password" ><br>
<label for="email" > Email </label><br>
<input type ="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit" >Submit</button>
</form>
And the jquery is:
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#Username').keyup(function(){ // Keyup function for check the user action in input
var Username = $(this).val(); // Get the username textbox using $(this) or you can use directly $('#username')
var UsernameAvailResult = $('#username_avail_result'); // Get the ID of the result where we gonna display the results
if(Username.length > 2) { // check if greater than 2 (minimum 3)
UsernameAvailResult.html('Loading..'); // Preloader, use can use loading animation here
var UrlToPass = 'action=username_availability&username='+Username;
$.ajax({ // Send the username val to another checker.php using Ajax in POST menthod
type : 'POST',
data : UrlToPass,
url : 'checker.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
UsernameAvailResult.html('<span class="success">Number available</span>');
}
else if(responseText > 0){
UsernameAvailResult.html('<span class="error">Number already taken</span>');
}
else{
alert('Problem with sql query');
}
}
});
}
});
$("#register").validate({
errorElement: 'div',
rules:{
"Username":{
required: true,
minlength:5
},
"password":{
required:true,
minlength:5
},
"Confirm_Password":{
required:true,
equalTo: "#password"
},
"email":{
required:true,
}
},
messages: {
Username:{
required: "Please provide a username",
minlength: "Your Username must be at least 5 characters long"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
Confirm_Password: {
required: "Please provide a confirm password",
equalTo: "Please enter the same password as above"
}
},
email:{
required: "Please provide a valid email",
}
});
});
</script>
Both work super, my doubt is how can I merge both, and also if the username is already taken the form should not submitted.
run a query in your php file to get all users with the current email i.e."example#example.com" and username i.e. "example" if you get any rows then it exists therefore don't add it, otherwise, add it!
$_GET['email'] = $email;
$result = mysql_query("SELECT * FROM users WHERE email='$email'");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
if(mysql_num_rows($result) >= 1) {
//show already registered
//you can either return false or change the return string/array to "registered"
} else {
mysql_query('INSERT INTO users ..............);
}
You could clear the username if its taken, thus causing the validation to fail
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
UsernameAvailResult.html('<span class="success">Number available</span>');
}
else if(responseText > 0){
UsernameAvailResult.html('<span class="error">Number already taken</span>');
//clear username
$('#Username').val('');
}
else{
alert('Problem with sql query');
//clear username
$('#Username').val('');
}
}
});
You can check the username on Keyup and form submit and prevent the form submit when username exists.
$("#register").submit(function( event ) {
if(usernameExists($('#Username').val()))
event.preventDefault();
});
$('#Username').keyup(function(){
usernameExists($(this).val();
});
usernameExists() should have all your current validation and ajax code as in your $('#Username').keyup(function(){ });
I am having a problem with the $_POST array that comes from my form.
Here is the code for my form:
<form id="form-add-client" method="post" data-ajax="false">
<input type="text" name="companyName" id="companyName" value="" placeholder="Company Name" />
<input type="text" name="email" id="email" value="" placeholder="Email" />
<br />
<input type="text" name="firstName" id="firstName" value="" placeholder="First Name" />
<input type="text" name="lastName" id="lastName" value="" placeholder="Last Name" />
<input type="tel" name="workPhone" id="workPhone" value="" placeholder="Work Phone" />
<input type="tel" name="mobilePhone" id="mobilePhone" value="" placeholder="Mobile Phone" />
<br />
<input type="text" name="streetAddress" id="streetAddress" value="" placeholder="Street Address" />
<input type="text" name="city" id="city" value="" placeholder="City" />
<input type="text" name="postalCode" id="postalCode" value="" placeholder="Postal Code" />
<br />
<input type="button" data-theme="b" name="submit" id="submit-add-client" value="Add Client" />
</form>
Here is the jQuery ajax code:
// Add Client
$(document).on('pagebeforeshow', '#add-client', function(){
$(document).on('click', '#submit-add-client', function() { // catch the form's submit event
if($('#companyName').val().length > 0 && $('#email').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
// fetch the data for the form
var data = $('#form-add-client').serialize();
$.ajax({url: 'http://www.website.co.nz/goflowdata/addclient.php',
data: data,
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#add-client-success");
} else {
alert('Add client unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
Here is the code from the addclient.php file:
<?php
header("Access-Control-Allow-Origin: *");
require_once("debug/chromephp.php");
$formData = $_POST;
ChromePhp::log($_POST);
require_once("config.php");
$companyName = $formData['companyName'];
$email = $formData['email'];
$firstName = $formData['firstName'];
$lastName = $formData['lastName'];
$workPhone = $formData['workPhone'];
$mobilePhone = $formData['mobilePhone'];
$streetAddress = $formData['streetAddress'];
$city = $formData['city'];
$postalCode = $formData['postalCode'];
$sql="INSERT INTO clients (companyName, email, firstName, lastName, workPhone, mobilePhone, streetAddress, city, postalCode) VALUES ('$companyName', '$email', '$firstName', '$lastName', '$workPhone', '$mobilePhone', '$streetAddress', '$city', '$postalCode')";
$result = mysql_query($sql);
if($result) {
// Success
$output = array('status' => true, 'massage' => 'Success!');
echo json_encode($output);
} else {
// Failed
$output = array('status' => false, 'massage' => 'Failed!');
echo json_encode($output);
}
?>
My problem is with the $formData['postalCode']; variable. It seems to be emtpy. I have used ChromePHP to try debug the issue and it returns the form data before being posted via ajax. In the serialized string the postalCode is there as you can see the console screenshot below. Can anyone see why this is happening? Any help is much appreciated.
When I use ChromePHP to log the contents of $_POST to the console I get this twice:
Object {companyName: "TestCompany", email: "test#email.com", firstName: "John", lastName: "Doe", workPhone: "01234567"…} city: "Testcity" companyName: "TestCompany" email: "test#email.com" firstName: "John" lastName: "Doe" mobilePhone: "012345678" postalCode: "" streetAddress: "7 Test Street" workPhone: "01234567" proto: Object
Screenshot:
Screenshot of MySQL table row:
Screenshot of console logged variables:
I have the below code for implementing a very basic login system on my site (using jQuery Mobile). The problem is that, when submitting the form through jQuery Mobile (and therefore using the validator), the validator always returns false and throws an error, even if the password is correct. When I wrote a separate form with nothing other than the two textboxes and a submit button and ran it directly to the validation script, it returned the correct value of true or false depending on the given password. What's wrong with the jQuery script that causes it to always return false?
HTML/JS:
<form action="logins.php" method="POST" id="loginForm" name="loginForm" data-ajax="false">
<label for="email" class="ui-hidden-accessible">Email Address:</label>
<input type="text" id="email" name="email" value="" placeholder="Email Address" />
<label for="pass" class="ui-hidden-accessible">Password:</label>
<input type="password" id="pass" name="pass" value="" placeholder="Password" />
<input class="submit" data-role="submit" type="submit" value="Submit" />
</form><br>
<br>
Return to home page
<script>
$('#login').bind('pageinit', function(event) {
$('#loginForm').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
email: {
required: true,
email: true
},
pass: {
required: true,
remote: {
url: "passcheck.php",
type: "post"
}
}
},
messages: {
email: {
required: "You must enter an email address.",
email: "You must enter a valid email address."
},
pass: {
required: "You must enter a password.",
remote: "Your username/password combination is incorrect."
}
}
});
});
</script>
PHP (passcheck.php):
<?php
require("common.php");
$query = "SELECT password FROM users WHERE email = :email";
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $conn->prepare($query);
$stmt->execute($query_params);
} catch(PDOException $ex) {
die("Failed to run query.");
}
$hash = $stmt->fetchColumn();
if(crypt($_POST['pass'], $hash) === $hash){
echo "true";
} else {
echo "false";
}
You should be using the submitHandler to write a function to handle the actual checking of the username/password via AJAX using AJAX Form: http://www.malsup.com/jquery/form/#api.
You don't have to use AJAX Form and can write your own method to handle the login checking using the jQuery ajax() method, but AJAX Form has it prewritten for you.
Also, you don't need the onkeyup, onblur, etc. there - all you need is onsubmit set to true. Your code should look like this:
<script>
$('#login').bind('pageinit', function(event) {
$('#loginForm').ajaxForm(); // Set as an AJAX Form - See Documentation Above
$('#loginForm').validate({
onsubmit: true,
rules: {
email: {
required: true,
email: true
},
pass: {
required: true
}
},
messages: {
email: {
required: "You must enter an email address.",
email: "You must enter a valid email address."
},
pass: {
required: "You must enter a password.",
}
},
submitHandler: function(form) {
$("#loginForm").ajaxSubmit();
}
});
});
</script>
I am trying to use the username taken or not using jquery validate plugin. but dosent seems to work. I would like to know where I went wrong, all other validation works fine. except for this.
jquery validate plugin page: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
javascript
<script type="text/javascript">
$(document).ready(function(){
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 2,
remote: "users.php"
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
},
email: "A valid email will help us get in touch with you.",
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('adduser.php', $("#register").serialize(), function(data) {
$("#register").fadeOut('fast', function(){
$('#results').html(data);
});
});
}
});
});
</script>
users.php
<?php
$request = $_REQUEST['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
register.php
<form name="register" id="register" method="post" action="">
<section>
<label for="username">Username:</label>
<div>
<input type="text" tabindex="1" class="input" id="username" name="username" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="email">email</label>
<div>
<input type="text" tabindex="2" class="input" id="email" name="email" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="password">Password</label>
<div>
<input type="password" tabindex="3" class="input" id="password" name="password" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="confirm_password">Confirm Password</label>
<div>
<input type="password" tabindex="4" class="input" id="confirm_password" name="confirm_password" value=""/>
</div>
</section>
<!--#-->
<br/>
<input type="submit" tabindex="5" id="submit" value="REGISTER" />
</form>
<div id="results"> </div>
thanks in advance.
I have the same but I use their validation and this to check if username exists. It works great.
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'username must have atleast 3 characters';
var checking_html = 'searching...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("checkuser.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html('<span class="is_available"><b>' +username + '</b> is available</span>');
//this is the id of my save button it'll display if available
$('#newacct').css("display", "inline");
}else{
//show that the username is NOT available
$('#username_availability_result').html('<span class="is_not_available"><b>' +username + '</b> is not available</span>');
}
});
}
</script>
First, you have an extra } that is closing your messages option prematurely, leading to the remaining messages being ignored. You should move this } after the confirm_password message block. Second, you should be calling jQuery.validator.format rather than jQuery.format. I believe this is why this particular validation rule doesn't work. Correct these and see if it works for you.
To answer the OP, you might want to use $_GET. Also, mysql_num_rows has been deprecated as of PHP 5.5.0, so you'll probably want to update that. You could just check if the query returns false.
<?php
$request = $_GET['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
?>
Try this......
JS
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 6,
remote: {
url: "Your PHP",
type: "post",
data: {
funct: 'user_check',
username: function() {
return $( "#username" ).val();
}
}
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
}
});
});
PHP
<?php
function user_check(){
$username = $_POST['username'];
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
}
?>
May help..