Summary: This is a basic, stand alone web form. Just html form, with a JQuery included for the functions.
I have a form that checks email and username for uniqueness and validity (of email). I'm using a JQuery onChange event to call each function, which is an Ajax call to a php file.
The JQuery for the username check is as follows:
$("#username").change(function() {
var username = $("#username").val();
var msgbox_username = $("#username_status");
var dataString = "username="+ username;
$("#username_status").html('<img src="images/loader.gif">Checking Availability.');
if (username != "" && username.length >= 6){
$.ajax({
Type: "POST",
url: "functions/check_username.php",
data: dataString,
success: function(msg_username) {
$("#username_status").ajaxComplete(function (event, request) {
if (msg_username == 'Username Ok') {
$("#username").removeClass("red").addClass("green");
msgbox_username.html('<font color="Green">Available</font>');
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html(msg_username);
}
});
}
});
return false;
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html('<font color="Red">Username of 6 or more characters is required</font>');
}
});
The check_username.php file is as follows:
<?php
$username = $_GET["username"];
include_once("../includes/connect.php");
$query = "SELECT username
FROM sss_users
WHERE username = '$username'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0 && strlen($username) >= 6) {
echo '<font color="#cc0000"><strong>' . $username . '</strong> is already in use. </font>';
} else {
echo 'Username Ok';
}
?>
Continuing with the pattern, the email JQuery:
$("#email").change(function() {
var email = $("#email").val();
var msgbox_email = $("#email_status");
var dataString = "email="+ email;
$("#email_status").html('<img src="images/loader.gif">Checking Availability.');
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
$("#email").removeClass("green").addClass("red");
msgbox_email.html('<font color="Red">Valid Email Required</font>');
} else {
$.ajax({
Type: "POST",
url: "functions/check_email.php",
data: dataString,
success: function(msg_email) {
$("#email_status").ajaxComplete(function (event, request) {
if (msg_email == 'Email Ok') {
$("#email").removeClass("red").addClass("green");
msgbox_email.html('<font color="Green">Available</font>');
} else {
$("#email").removeClass("green").addClass("red");
msgbox_email.html(msg_email);
}
});
}
});
return false;
}
});
And the email PHP:
<?php
$email = $_GET["email"];
include_once("../includes/connect.php");
$query = "SELECT email
FROM sss_users
WHERE email = '$email'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0) {
echo '<font color="#cc0000"><strong>' . $email . '</strong> is already in use. </font>';
} else {
echo 'Email Ok';
}
?>
They each work seperately, but if I put an invalid username in the box and then put a valid email, somehow the check_username.php file is called and no matter what is in the box (valid or not) it thinks it's a valid username.
An example is:
All functions are called on the OnChange Event
1) type in the username asdfasdf (which is available)
2) Delete the username asdfasdf from the text box (this works correctly, displaying a username must have at least 6 characters)
3) type in any valid email
Result: the valid email works correctly, but the username field (which is blank) recalls what was there before (asdfasdf) and says it is a valid username (even though the field is still blank.)
Hope this makes sense. Any suggestions?
SOLUTION
As noted below, the .ajaxComplete() was calling all functions with that tag. Therefore, when I made the following changes it worked:
$("#username_status").ajaxComplete(function (event, request) { ... code here ... });
changed to:
$("#username_status").ajaxComplete(function (event, request, settings) { ... code and new if statement ... });
And then I wrapped
if(settings.url == 'functions/check_username.php') {}
around the validation code. This process was done for both the username and email validation.
http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
Maybe both handlers are being fired.
Related
I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.
I'm working on a webpage in which, when the user checks a checkbox, calling a PHP function to query the table if the user exists. If so, it then displays the button to go to next page.
So far I've tried this. I am sure that my php is working fine I checked my result variable returns 0 when user exists, but for some reason it is not executing the if statement.
$(document).ready(function() {
$('#submit').hide();
$('#mobiletask').change(function(){
if($('#mobiletask').attr('checked'))
{
check_availability();
// $( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
});
//function to check username availability
function check_availability(){
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == 0) {
//show that the username is NOT available
$('#submit').show();
}
});
}
checkusername.php
$username = mysql_real_escape_string($_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select studentId from smartphone_scores where studentId = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
Based on the response you are getting:
<html><body>1</body></html>
What you have to do is to work on your PHP file and make sure to remove any HTML in it.
Try this:
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == '1'){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == '0') {
//show that the username is NOT available
$('#submit').show();
}
});
$(document).ready(function()
{
$('#submit').hide();
$('#mobiletask').on('change',function() {
if($('#mobiletask').attr('checked'))
{
check_availability();
//$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
function check_availability()
{
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.ajax({
url: 'check_username.php',
type: 'POST',
async: false,
data: {'name':'username','value':username},
success: function(result)
{
alert(result);
//if the result is 1
if(result == '1')
{
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}else if(result == '0')
{
//show that the username is NOT available
$('#submit').show();
}
}, error: function(error)
{
alert(error);
}
});
}
});
** Remove the alerts when done with testing the code. **
I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // 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
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.
I apologise if this comes across as really stupid. I have searched but can't seem to find an answer. I hope I can explain what it is I am trying to do.
I want to be able to query a database and if there is a record in it to show the record in the span/div or show a not found error message if there isn't.
I have a jquery check up and running to check if a username is in the database, what I want to know is how easy it would be to ammend this to pull all the data and show it in the span/div on the original page.
This is the jquery I have:
$(document).ready(function () {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if (username == "" || username.length < 2) {
$('#username').css('border', '1px #D5D5D5');
$('#cross').hide();
$('#tick').hide();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function (response) {
if (response == 1) {
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
Can I do all this on the one page and query the db from the same page, instead of posting it to another page as I don't know how to get the results back to the calling page?
I hope I have explained what I want to do. Apologies if I haven't
Here is the PHP code:
$username = trim(strtolower($_POST['username'])); $username = mysql_escape_string($username); $query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1"; $result = mysql_query($query); $num = mysql_num_rows($result); echo $num; mysql_close()
You will normally send ajax requests to pages hosted on your server. So you can't directly access your database without going through your server. You'll need to write a function on your server that queries the database, and then call that function from javascript using ajax.
You can output a string in PHP and then set that text value to an element with jQuery ( $('#element').val(responseFromServer);
or $('#element').html(responseFromServer);
Instead of sending back "1" send back a json response something like:
/* record exists */
{status:1, html:'server generated message about record'}
/* doesn't exist */
{status:0}
This will allow you to still change css based on response data status value
Can use $.post ajax shorthand method:
$.post('check.php',{username: username}, function(response){
var upDateElement=$('#spanID');
if(response.status && response.status== 1){
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
upDateElement.html( response.html)
}else{
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
upDateElement.html('Message html for no record found')
}
},'json')
check.php
$data = array();
$data['exists'] = false;
if(!isset($_POST['username'])) {
echo json_encode($data);
exit();
}
$username = mysql_escape_string($_POST['username']);
$query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(count($row) == 1) {
$data = $row;
$data['exists'] = true;
}
return json_encode($data);
from your jQuery:
success: function(response) {
/**
* For instance, for a table with id, username, password and email you have
* data.exists = true/false;
* data.id = 1;
* data.username = 'foo';
* data.password = 'sample data password';
* data.email = 'foo#bar.com';
*/
if(response.exists === true) {
$('#username').val(response.username);
$('#email').val(response.email);
}
}