Reputation: 135
i have a php code to check if a user already exists in my db , but i would like it to go through jquery first .
This way instead of getting an error message on a new page , the user simply gets a message that the user already exists and can change the name.
Looks like this :
PHP CODE:
<?php
$link = mysqli_connect("localhost","root","","data1") or die("Error " . mysqli_error($link));
$usercheck = "csdcsdsdf";
$sanitizeduser= filter_var($usercheck, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$result = $link->query("SELECT username FROM users WHERE username = '".$sanitizeduser."' ");
$row_cnt = $result->num_rows;
if($row_cnt>0){
echo "User Exists";
}else{
echo "No User found";
}
?>
I'm using a predefined jquery code (this script : http://jqueryvalidation.org/)'
part of my jquery code to validate names :
names: function(value, element) {
return this.optional(element) || /^\w+$/.test(value);
},
Full Jquery code :
file 1 : http://jsfiddle.net/EjSbd/1/ (script.js)
file 2 : http://jsfiddle.net/qM4Uz/1/ (jquery.validate.js)
Upvotes: 0
Views: 1125
Reputation: 935
If you are using jQuery validation plugin then here is the solution. This is active code. you need to use remote: . This is my existing code. This will help you to get idea.
$("form#form-join-1").validate({
rules: {
sponsorID: {
required: true,
minlength: 5,
remote: "ajax.php"
},
slcchild: {
required : true,
remote : {
url: "ajax.php",
type: "post",
data: {
action : 'child-validation',
parent_node : function(){
return $('input#sponsorID').val();
}
}
}
}
},
messages: {
sponsorID: {
required: "Enter a Sponsor ID",
minlength: $.format("Enter at least {0} characters"),
remote: $.format("{0} is already in use")
},
slcchild: {
required: "Select A node",
remote: $.format("{0} is not empty")
}
}
});
Here is complete guideline. Following this link. They have example code. http://imamiscool.wordpress.com/2009/06/29/check-email-availability-using-jquery%E2%80%99s-ajax-part-2-easy-way/
Upvotes: 1
Reputation: 147
One of the easier ways is to use one of jQuery's Ajax functions, .load()
So first you make an HTML div where you want your dynamically generated content to be:
<div id="area_to_load_at">
This text will be replaced when JS runs changeArea()
</div>
Next you make a Javascript function that's just for changing the div:
function changeArea()
{
var loadTo = "#area_to_load_at";
var loadFrom = "your_file_that_checks_if_the_username_is_taken.php";
$(loadTo).load(loadFrom);
}
Then anywhere in the Javascript where you want it, like right after your validation, just call:
changeArea();
Upvotes: 0
Reputation: 22711
Try this, You need to add remote: "usernamecheck.php"
Assumed your php file name is usernamecheck.php
username: {
minlength: 5,
maxlength:20,
required: true,
wordonly: true,
remote: "usernamecheck.php"
},
Ref: http://jqueryvalidation.org/category/methods/
Upvotes: 0