I'm working on a simple form and validating it through javascript php and AJAX.
Here is the html form snippet just for the password:
Password:
<input type="password" name="password" id="password"
onblur="checkUserInputs('password')"
<span id="password-warning"></span>
<input type="button" name="signup" id="signup"
value ="Sign Up" class="button signup-button"
onclick="signUp()">
<span id="status-field"></span>
Here is the checkUserInput() snippet that fires up on onblur event:
function checkUserInputs(inputId){
var inputField = document.getElementById("password");
var varName = "checkPassword"; /variable name to send to php
var functionToCall = "check_password";//php calls corresponding function based on this string value
if(inputField.value != ""){
//creates ajax object
var ajax = createAjax("POST", "core/proccess_signup.php");
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(ajaxReady(ajax)){
//display error massage
warningDiv.innerHTML = ajax.responseText;
}
}
//now data to php scripts for validation ajax.send(varName+"="+inputField.value+"&functionToCall="+functionToCall);
}
}
SignUp() fires up when clicking signup button:
function signUp(){
var password = document.getElementById("password").value;
//rest of the code to get other inputs values...
//status div to display errors
var statusDiv = document.getElementById("status-field");
if(password !="")//I have other checks too, just shortened the code here {
//setup ajax
var ajax = createAjax("POST", "core/proccess_signup.php");
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(ajaxReady(ajax)){
if(ajax.responseText == "success"){ //registartion was successful
document.getElementById("signup-form").innerHTML =
"Registration was successful";
}else{
statusDiv.innerHTML = "Please check the error massages";
}
}
}
//send all of the data to php scripts for validation ajax.send("functionToCall=signup&username="+username+"&password="+password);
}else{
statusDiv.innerHTML = "Please fill out all of the form data";
return;
}
}
Validate the data in php:
$functionToCall = $_REQUEST['functionToCall'];
if($functionToCall == "check_password"){
check_password();
}else if($functionToCall == "signup"){
check_password();
signup();
}
function check_password(){
if(isset($_POST['checkPassword'])) {
$pass = $_POST['checkPassword'];
if(strlen($pass)< 6 || strlen($pass) > 20){
echo 'password must be min 6 and max 20 characters';
exit();
}
if(preg_match("/\s/", $pass)) {
echo 'Password can not be empty or contain spaces';
exit();
}
echo '';
return true; //if all is good return true so i can check if password validation passed successfully
}
}
Here is the signup function
function signup(){
if(isset($_POST['username'])) {
//here I check just the password
if(check_password()){
echo 'success';
exit();
}
}
well if password entered correctly with no white spaces and length between 6-20, check_password() should be set to true and echo 'success' should be executed, but it DOESN'T. this drives me nuts.
Why echo 'success' never gets executed? Take a look at the code and tell me what I'm doing wrong.
The main problem that I can see is that the check_password function looks for isset($_POST['checkPassword']).
That function is called again by the second ajax request, which doesn't post that value. It posts password.
I would strongly recommend using xdebug if you aren't already. It really helps when stepping through this kind of thing. xdebug
Here's a quick fix to pop in check_password function.
if(isset($_POST['checkPassword']) || isset($_POST['password']) ) {
$pass = (isset($_POST['checkPassword']) ) ? $_POST['checkPassword'] : $_POST['password'];
Also you call the check_password function twice. It might be better to store the return value of that as a variable then pass as a parameter.
First call
if($functionToCall == "signup"){
check_password();
signup();
Second Call (in signup function)
if(check_password()){
echo 'success';
exit();
}
I had to mess with the js a little to make that work , but I'm guessing that was just some mishaps in abbreviating the code for simplicity.
Changes:
Ajax request wasn't working, so edited.
username var wasn't set, so hardcoded to foobar.
Here is the full html page
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>TEST</title>
<script>
function checkUserInputs(inputId){
var inputField = document.getElementById("password").value;
var varName = "checkPassword";
var functionToCall = "check_password";
var warningDiv = document.getElementById("password-warning");
if( inputField != ""){
var params = varName + "=" + inputField + "&functionToCall=" + functionToCall;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
warningDiv.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","core/proccess_signup.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( params );
}
}
function signUp(){
var password = document.getElementById("password").value;
//rest of the code to get other inputs values...
//status div to display errors
var statusDiv = document.getElementById("status-field");
if(password !=""){ //I have other checks too, just shortened the code here
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if( xmlhttp.responseText == "success"){ // registration was successful
statusDiv.innerHTML = "Registration was successful";
}
else{
statusDiv.innerHTML = "Please check the error messages";
}
}
}
xmlhttp.open("POST","core/proccess_signup.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("functionToCall=signup&username=foobar&password="+password);
}
else
{
statusDiv.innerHTML = "Please fill out all of the form data";
return;
}
}
</script>
</head>
<body>
<input type="password" name="password" id="password" onblur="checkUserInputs('password')" />
<span id="password-warning"></span>
<input type="button" name="signup" id="signup" value ="Sign Up" class="button signup-button" onclick="signUp()" />
<span id="status-field"></span>
</body>
</html>
Here is the php (I haven't taken out the duplicate function call)
<?php
$functionToCall = $_REQUEST['functionToCall'];
if($functionToCall == "check_password"){
check_password();
}else if($functionToCall == "signup"){
check_password();
signup();
}
function check_password(){
if(isset($_POST['checkPassword']) || isset($_POST['password']) ) {
$pass = (isset($_POST['checkPassword']) ) ? $_POST['checkPassword'] : $_POST['password'];
if(strlen($pass)< 6 || strlen($pass) > 20){
echo 'password must be min 6 and max 20 characters';
exit();
}
if(preg_match("/\s/", $pass)) {
echo 'Password can not be empty or contain spaces';
exit();
}
echo '';
return true; //if all is good return true so i can check if password validation passed successfully
}
}
function signup(){
if(isset($_POST['username'])) {
//here I check just the password
if(check_password()){
echo 'success';
exit();
}
}
}
Related
Still havent solved this. Can someone help me with my new, updated code. The new code is at the bottom of this post.
Im learning PHP and right now Im trying to learn to pass data from JS to PHP using AJAX.
This is my form:
<form id="login">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
required>
<label><b>Password</b></label>
<input type="password" name="password" id="password"
required>
<button type="button" id="submitLogin">Login</button>
</form>
First I have a function, something like this:
try {
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}else{
Do stuff }
}
catch(error){ alert('"XMLHttpRequest failed!' + error.message); }
After this, Im trying to send my form data to a php-file, using new FormData(), but Im not really sure how to do this. Right now I have a code like this:
if (getElementById('username').value != "" & getElementById('password').value != "") {
request.addEventListener('readystatechange', Login, false);
request.open('GET', 'login.php', true);
request.send(new FormData(getElementById('login')));
}
The login-function is a function to test
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
In my PHP-file I have a function looking like this right now:
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_GET['login'])) {
$Username = isset($_GET['username']) ? $_GET['username'] : '';
$Password = isset($_GET['password']) ? $_GET['password'] : '';
if (isset($logins[$Username]) && $logins[$Username] == $Password){
do stuff
}
What more do I need to pass my form data from the js-file to the php-file, so I can check if the input data is the same as the data I have in the array?
-----------------------------------------------------------------------
New code:
function LoginToSite() {
if (getElementById('username').value != "" && getElementById('password').value != "") {
request.addEventListener('readystatechange', Login, false);
var username = encodeURIComponent(document.getElementById("username").value);
var password = encodeURIComponent(document.getElementById("password").value);
request.open('GET', 'login.php?username='+username+"&password="+password, true);
request.send(null);
}
}
function Login() {
if (request.readyState === 4 && request.status === 200) {
alert("READY");
var myResponse = JSON.parse(this.responseText);
getElementById("count").innerHTML = myResponse;
getElementById('login').style.display = "none";
if(request.responseText == 1){
alert("Login is successfull");
}
else if(request.responseText == 0){
alert("Invalid Username or Password");
}
}
else{
alert("Error :Something went wrong");
}
request.send();
}
session_start();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username != '' and $password != ''){
foreach($user_array as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}
}else{
echo "0";
}
When im trying to login, the site first alert that something went wrong, then the same thing happens again and after that, it alerts "ready". What do I have to change to get this right?
Try running the following code.
HTML :
<form id="login">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
required>
<label><b>Password</b></label>
<input type="password" name="password" id="password"
required>
<button type="button" id="submitLogin">Login</button>
</form>
JavaScript:
function submitLogin{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var http = new XMLHttpRequest();
var url = "login.php";
var params = "username="+username+"&password="+password;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
if(http.responseText == 1){
alert("Login is successfull");
}
else{
alert("Invalid Username or Password");
}
}
else{
alert("Error :Something went wrong");
}
}
http.send(params);
}
PHP:
<?php
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_POST['username']) && isset($_POST['password'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
foreach($logins as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}
}else{
echo "0";
}
?>
I hope this helps you.
Basically you need something like this (JS side)
// create and open XMLHttpRequest
var xhr = new XMLHttpRequest;
xhr.open ('POST', 'login.php'); // don't use GET
// 'onload' event to handle response
xhr.addEventListener ('load', function () {
if (this.responseText == 'success')
alert ('successfully logged in.');
else
alert ('failed to log in.');
}, false);
// prepare and send FormData
var fd = new FormData;
fd.append ('username', document.getElementById("username").value);
fd.append ('password', document.getElementById("password").value);
xhr.send (fd);
PHP code (login.php) may look like this.
# users array
$logins = array ( 'username1' => 'pwd1', 'username2' => 'pwd2' );
# validate inputs
$u = isset ($_POST['username']) ? $_POST['username'] : false;
$p = isset ($_POST['password']) ? $_POST['password'] : false;
# check login
if ($u !== false && $p !== false && isset ($logins[$u]) && $logins[$u] == $p)
echo "success";
else
echo "error";
Course, it's recommended to check do functions XMLHttpRequest and FormData exist first.
if (window['XMLHttpRequest'] && window['FormData']) {
/* place your Ajax code here */
}
This code is inside a JavaScript function triggered by the onsubmit event of a form.
var username = document.register.username.value;
var phpUsernameFree = <?php
$username = "<script>document.write(username)</script>";
$resultTempUsers = mysql_query("SELECT * FROM tempUsers WHERE username = '$username' ") or die(mysql_error());
if( mysql_num_rows($resultTempUsers) == 0 ){
echo 1;
};
?> ;
if( phpUsernameFree == 0){
toggleNew('usernameAlreadyExists', 1);
usernameCounter = 1;
}
I want that if the username already exists in the database a window is shown telling the user that the username already exists.
I've tried deleting all of the php code and simply replacing it by 'echo 1' or 'echo 0', and that worked, so I know that code executes.
I think there's a problem in the attempt to read information from the database.
EDIT:
Okay I've tried doing this with Ajax, didn't work so far. I downloaded jQuery and I'm trying out this code now:
usernameTaken = checkUserExistence(username, 'username');
if( usernameTaken == 1){
toggleNew('usernameAlreadyExists', 1);
usernameCounter = 1;
}
function checkUserExistence(str, type){
var dataString = 'str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existance.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
return 1;
}else{
return 0;
}
}
});
}
return false;
}
my existance.php looks like this:
<?php
*include connection to database here*
$data = $_POST["data"];
$type = $_POST["type"];
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
?>
Currently what happens when using this code is, when I press the submit button, the value changes to 'Sending...' as in the beforeSend attribute, but nothing else happens.
You need AJAX to do that, if you do not want to use Jquery.
Something like this:
<script>
function Login(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("Msg").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "Login.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
Login.php:
$username = $_REQUEST["q"];
$resultTempUsers = mysql_query("SELECT * FROM tempUsers WHERE username = '$username' ") or die(mysql_error());
if( mysql_num_rows($resultTempUsers) == 0 ){
echo "User free";
}else{
echo "User exist";
}
something like that, don't work but is an idea.
The best way is using ajax. you should do something like this:
$("#inputId").keyUp(function(){
//This event, raised when the textbox value changed
//inside this event, you can call ajax function and check user existance and if result is false you can disable the submit button
});
In stead of submit button use normal button, submit form after ajax response depending on the response value.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script>
function checkUserExistence(){
var username = document.register.username.value;
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest();} else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
phpUsernameFree = xmlhttp.responseText;
if( phpUsernameFree == 0){
alert("username Already Exists");
} else {
alert("username available.");
register.submit();
}
} else if(xmlhttp.status == 400) {
alert("There was an error 400");
} else {
alert("something else other than 200 was returned");
}
}
}
xmlhttp.open("GET", "service.php?username=" + username, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="register" name="register" method="post">
<input type="text" name="username" id="username" value="check" />
<input type="button" id="save" name="save" value="Save" onclick="checkUserExistence();" />
</form>
</body>
</html>
<!-- service.php -->
<?php
$username = $_REQUEST["username"];
$resultTempUsers = mysql_query("SELECT * FROM tempUsers WHERE username = '$username' ") or die(mysql_error());
if( mysql_num_rows($resultTempUsers) == 0 ){
echo 1;
};
?>
i am trying to validate a form along with a php script.
validations are perfectly working, but if i submit correct details the button is not clicked.
when i dont enter any details the msg of required field is displayed.
when i enter wrong details the alert message is displayed.
but when i enter correct details the login button is not clicked.
In alls() function i tried to return true but then the problem that it gets refreshed after displaying the required field message for a second.
HTML code:
<form id="frm_login" method="post" name="frm_login" onSubmit="return alls()">
UserName: <input type="text" name="txt_usrnm" /><label id="i"></label>
<br/><br/>
Password: <input type="password" name="pswd" /><label id="i1"></label>
<br/><br/>
<input type="submit" name="submit" value="Login" style:"width=10px"/>
Forgot Password ?
<br/><br/>
<font size="+1">Register Here</font>
</form>
Javascript:
<script type="text/javascript">
function req()
{
if (document.frm_login.txt_usrnm.value=="")
{
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
document.getElementById('i').style.fontSize="12px";
}
if (document.frm_login.pswd.value=="")
{
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
document.getElementById('i1').style.fontSize="12px";
}
return false;
}
function validateUname()
{
submitFlag = true;
var len=document.frm_login.txt_usrnm.value.length;
if((len>0) && (len<6)){
submitFlag=false;
document.getElementById('i2').innerHTML="*Enter atleast 6 characters";
document.getElementById('i2').style.color="red";
document.getElementById('i2').style.fontSize="12px";
}
return submitFlag;
}
function alls()
{
req();
validateUname();
//CheckPassword(this);
//num();
//confirm_pswd();
//namevalid();
//ValidateEmail(this);
return false;
}
</script>
PHP code:
<?php
if(isset($_POST['submit']))
{
$usrnm1=$_POST['txt_usrnm'];
$pswd1=$_POST['pswd'];
$user_name = "root";
$password = "";
$database = "show_your_talent";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$res="select * from username where UserName='$usrnm1' and Password='$pswd1'";
$result2 = mysql_query($res,$db_handle);
$count=mysql_num_rows($result2);
if($count==1)
{
$_SESSION['user'] =$usrnm1;
//echo $_SESSION['user'];
header("Location: category.php");
}
else
{
//$_SESSION['user']="false";
echo "<script type='text/javascript'> alert('Incorrect UserName/Password.')</script>";
//header('Location: index.php');
}
mysql_close($db_handle);
}
?>
You submit function, alls(), always returns false which means form will not submit. Try this:
function req() {
var submitFlag = true;
if (document.frm_login.txt_usrnm.value == "") {
submitFlag = false;
document.getElementById('i').innerHTML = "*This field is required";
document.getElementById('i').style.color = "red";
document.getElementById('i').style.fontSize = "12px";
}
if (document.frm_login.pswd.value == "") {
submitFlag = false;
document.getElementById('i1').innerHTML = "*This field is required";
document.getElementById('i1').style.color = "red";
document.getElementById('i1').style.fontSize = "12px";
}
return submitFlag;
}
function validateUname() {
submitFlag = true;
var len = document.frm_login.txt_usrnm.value.length;
if ((len > 0) && (len < 6)) {
submitFlag = false;
document.getElementById('i').innerHTML = "*Enter atleast 6 characters";
document.getElementById('i').style.color = "red";
document.getElementById('i').style.fontSize = "12px";
}
return submitFlag;
}
function alls() {
var valid = true;
valid *= req();
valid *= validateUname();
//CheckPassword(this);
//num();
//confirm_pswd();
//namevalid();
//ValidateEmail(this);
return valid ? true : false;
}
which will prevent form from submitting when req() or validateUname() returns false.
alls() always returns false. Hence you form is never submitted.
When onsubmit callback returns false, the submission to the server is stopped.
I'm trying to validate a form with JavaScript. It prints error messages when input fields are empty. The problem I'm having is that the code doesn't fire on submit.
http://jsfiddle.net/LHaav/
Here is the HTML code:
<head>
...
<script type="text/javascript" src="./js/validate.js"></script>
....
</head>
...
<form name="submitForm" method="post" id="submitBetaForm" onsubmit="return(validate())" action="validate.php" class="form-style">
<label for="email">Email:</label>
<input type="text" id="email-beta" name="email" placeholder="Enter Email"/>
<label for="firstName">Name:</label>
<input type="text" id="firstName" class="half-width" name="messageName" placeholder="First name"/>
...
Here is the JavaScript code:
function validate()
{
var email = document.submitForm.email;
var first = document.submitForm.firstName;
var last = document.submitForm.lastName;
var message = document.getElementById('warning');
message.innerHTML = 'This is working!';
var newLineCharNum = 0, poemContentArray = 0;
//check to make sure that there is actually new line in the
//text area. Ensure that code doesn't blow up.
if(textarea.value.match(/\n/g) != null)
{
newLineCharNum = textarea.value.match(/\n/g).length;
poemContentArray = textarea.value.split("\n");
}
//check for email, firstName, lastName
//focus puts the cursor on the element that needs to be corrected.
var lineNum = newLineCharNum + 1;
// if(email.value.length > 30)
// {
// message.innerHTML = 'Email should be less than 30 character';
// title.focus();
// return false;
// }
else if(email.value.length == 0 || title == "")
{
message.innerHTML = 'Please enter your email';
title.focus();
return false;
}
if (firstName.value.length > 30)
{
message.innerHTML = 'First name should be less than 30 character';
authorName.focus();
return false;
}
else if(firstName.value.length == 0 ||authorName == "")
{
message.innerHTML = 'Please enter your first name';
authorName.focus();
return false;
}
if (lastName.value.length > 30)
{
message.innerHTML = 'Last name should be less than 30 character';
authorName.focus();
return false;
}
else if(lastName.value.length == 0 ||authorName == "")
{
message.innerHTML = 'Please enter your last name';
authorName.focus();
return false;
}
}
And PHP here:
<?php
session_start();
include('connection.php');
if(isset($_POST['SEND'])){
//get information from the form
$email = $_POST['email'];
$first_name = $_POST['messageName'];
$last_name = $_POST['messageLast'];
$interest = $_POST['interest'];
$country = $_POST['country'];
// Check connection
if ($con)
{
$insert_query = "INSERT INTO `user` (`id`, `first_name`, `last_name`, `interest`, `country`, `time`, `email`)
VALUES (NULL, '$first_name', '$last_name', '$interest', '$country', CURRENT_TIMESTAMP, '$email')";
$con->query($insert_query);
$con->close();
echo "here";
}
else{
echo "ERROR!";
}
//store informationn in the sessiont for later use
$_SESSION['email'] = $email;
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['interest'] = $interest;
$_SESSION['country'] = $country;
}
?>
It turns out that your example is full of bad variable names and references. Your using firstNmae when you should be using first, for instance.
I've corrected some of them and it's apparently working: http://jsfiddle.net/LHaav/1/
You just have to be aware of the JS errors in your browser console and you'll be fine. ;)
You got a good few problems in your Javascript - undefined variables everywhere. But the main problem is that your Javascript in that fiddle is not being executed at all. If you change your form handler to onsubmit="return validate()" you'll see that validate is not defined, although this may be down to how the JS is loaded in the fiddle.
Regardless, to alleviate this problem move your script out of the head and put it in the bottom of the page, just the before the closing body tag. You'll at least now hopefully hit the validate method.
http://jsfiddle.net/LHaav/2/
Now you'll have to take care of all those undefined variables.
I have been following a tutorial and the person who does it provide the code for you to use, so ive tried using the code and going through it line by line but as i hardly know anything about ajax, i cant seem to understand why it is not passing data through to the page that is specified,and since the data isnt being passed through the process of mysqli queries and all other things, they wont begin to happen as the data isnt being passed over.
The data is part of a form and it is to check usernames against the database to check availability, so the code for the data in the form is ...
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">...
And so on... the js provided is ..
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signupfunc.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
So as far as i understand, var u= _("username").value is the value of the input with the id=username, and if username is not blank then it firstly brings up the checking... before starting the var that is called ajax, it begins the process of POSTing to the page, signupfunc.php, then im not exactly sure the next bit but i think it means something like if something returns from the var ajax then it puts the response return in the unamestatus div ?? then the last bit does as it says? the var ajax sends the value of usernamecheck as the username... but it is not sending the data to the specified page ... can someone point out what im doing wrong advise how to solve this problem ??
and just incase it is needed here is the code that is on the specified page signupfunc.php that is related to the code above..
//Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
maybe you can try change you code with below jquery ajax code :
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
$.ajax({
url : "signupfunc.php",
type : "POST",
data : "usernamecheck="+u,
dataType : 'text',
success: function(data,textStatus,jqXHR){
alert(data);
}
})
}