I am trying to check inserting username is correct or not using jquery and php.. if username is not match with the value from database, it should be trigger an alert saying 'your user name is wrong'.
I tried this but I couldn't figure this out. When I type an username alert message triggering for each letter. But I need to check given value with database after entering in text field.
This is my Jquery -
// --- Check Username Availability for successful login --- //
$('#loginusername').keyup(function() {
var checkname=$(this).val();
var availname=remove_whitespaces(checkname);
if(availname!=''){
var String = 'username='+ availname;
$.ajax({
type: "POST",
url: "emailCheck.php",
data: String,
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result == $('#loginusername').val()){
alert('Your entered Username is ok');
} else {
alert('Your entered Username is wrong');
}
}
});
}
});
This is from emailCheck.php
if(isset($_POST['username']) && !empty($_POST['username'])){
$userName = mysqli_real_escape_string($dbc, $_POST['username']);
$q = "SELECT username FROM userlogin
WHERE username = '$userName'";
$r = mysqli_query($dbc, $q);
$count = mysqli_num_rows($r);
$HTML='';
if($count == 1){
$HTML='username exists';
}else{
$HTML='';
}
echo $HTML;
}
Because you are using keyup event of textbox, use blur OR change event of textbox.
Edit
Change
if(result == $('#loginusername').val())
to
if(result == '')
Because you are sending blank result when no match found.
Well, in your JS, you're comparing what the user entered to what the PHP script returns:
result == $('#loginusername').val()
But the only thing your PHP script can return is the string 'username exists' or an empty string:
if($count == 1){
$HTML='username exists';
}else{
$HTML='';
}
Try just using alert(result).
var timer;
var time = 2000;
$('input').keyup(function() {
// when user stop typing for {time} second, do next function
timer= setTimeout(doSomething, time);
)
$('input').keydown(function() {
// when user continue typing clear timer
clearTimeout(timer);
)
function doSomething() {
}
try this
Change echo $HTML; to echo '{"success":"true", "usernameExists":"' + $count + '"}';
Then amend your Javascript to this
...
$.ajax({
type: "POST",
url: "emailCheck.php",
data: {username: availname},
cache: false,
success: function(result){
if(result.usernameExists == 1){
alert('Your entered Username is ok');
} else {
alert('Your entered Username is wrong');
}
}
});
instead of using keyup use 'onchange'
You can use the .blur trigger. http://api.jquery.com/blur/
// --- Check Username Availability for successful login --- //
$('#loginusername').blur(function() {
var checkname=$(this).val();
var availname=remove_whitespaces(checkname);
if(availname!=''){
var String = 'username='+ availname;
$.ajax({
type: "POST",
url: "emailCheck.php",
data: String,
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result == $('#loginusername').val()){
alert('Your entered Username is ok');
} else {
alert('Your entered Username is wrong');
}
}
});
}
});
first of all you should change the event that your firing your check code. right now your firing at every keyup. I suggest change this to change
$('#loginusername').change(function() {
second there is an issue with your json response. In your php side your responding with an empty string when username is not found and an error message when the username is found. But your javascript side is expecting the return value to be the same as the username the user typed in the textbox when the string is available.
To meet this requirement lets change your php side of the code.
$HTML='';
if($count == 1){
$HTML='username exists';
}else{
$HTML=$_POST['username'];
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Ajax:
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
type: "POST",
url: "http://localhost/test/testForm.php",
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
PHP:
<?php
require_once("Connections/cid.php");
$userId= $_POST['userId'];
$productCode= $_POST['productCode'];
$countryCode= $_POST['countryCode'];
$sql_check = "SELECT * FROM utc WHERE userId = '$userId' AND productCode = '$productCode' AND countryCode = '$countryCode'";
$list = mysqli_query( $conn, $sql_check);
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
else
echo "NOK";
?>
I am very sure that the data i had pass in to the php file are correct. However i cant seem to get my data to the php file and it keep return false value back to me. Anything i can do to make it works?
**Note: Somehow even if i change both result to return true in ajax, it will still return false.
and i tried to change the link to another file with only echo "OK"; but it also doesn't work. So i think it is not the file problem. It just never run the ajax no matter what. Do i need to do any link for ajax to run? **
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
url: "test/testForm.php"
type: "POST",
url: "http://localhost/test/testForm.php", // This needs to be "test/testForm.php"
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
Adjust this code according your input type. I hope this will help you:
$(document).ready(function() {
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_phone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if(user_name==""){
$('input[name=name]').css('border-color','red');
proceed = false;
}
if(user_email==""){
$('input[name=email]').css('border-color','red');
proceed = false;
}
if(user_phone=="") {
$('input[name=phone]').css('border-color','red');
proceed = false;
}
if(user_message=="") {
$('textarea[name=message]').css('border-color','red');
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function() {
$("#contact_form input, #contact_form textarea").css('border-color','');
$("#result").slideUp();
}); });
Try this also both are running on my localhost:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function (d) {
alert(d);
}
});
});
});
</script>
<form method="post" id="myform">
<input type="text" name="time" /><br>
<input type="text" name="date" /><br>
<input name="submit" type="submit" value="Submit">
</form>
make new file of post.php and pest this code. This code will alert your input field value:
<?php print_R($_POST); ?>
"my current folder is localhost/abc/bsd.php while the one that i am going is localhost/test/testForm.php".
From the above comment, you have to change the ajax url to
url: "/test/testForm.php",
Apart from this , your php code shows
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
This is incorrect as mysqli_fetch_assoc returns an associative array of strings. So, the comparison $num >0 is illogical.
I have an error where I can't proceed my login_process.php using ajax. I have stored all my files as a one folder. If I run my HTML log in page, the error is appeared. Below is my code. It is just a simple code. Before this, I have applied the similar code as below (except for login_process.php because I've put a few functions) as my homework. But when I've try to make it again, as i said, the browser, either in Chrome or Firefox, displays an error as I wrote in ajax below.
index.html(ajax part)
$(document).ready(function(){
$("#subBTN").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var status = $("#statusAlert");
if(username === "" && password === ""){
status.html("<span>Username and password are both required!</span>");
}
else if(username === ""){
status.html("<span>What is your username?</span>");
}
else if(password === ""){
status.html("<span>What is your password?</span>");
}
else{
$.ajax({
url:'login_process.php',
type: 'post',
data: {"?admin_name=": username, "&admin_pass=": password},
dataType: 'html',
success: function(data){
//alert(data);
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
}
});
}
});
});
login_process.php
<?php
session_start();
if($_POST):
$username = $_POST["username"];
$password = $_POST["password"];
if($username):
echo "Hi " . $username;
endif;
endif;
?>
You got a error in jQuery ajax call in passing data
You use :
data: {'admin_name':username, 'admin_pass': password},
instead of
data: {"?admin_name=": username, "&admin_pass=": password},
Or access in php code data to use:
$_POST['admin_name'] AND S_POST['admin_pass']
You should change this line of code
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
To
if(data.Length > 0){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
I am using AJAX to call a PHP script. I am using conditions to echo the proper error message in my PHP. When I do this, my AJAX and JQUERY do not work properly.
My JQUERY/AJAX:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
e.preventDefault();
}
if (taken == 1) {
alert('email taken');
e.preventDefault();
}
}
});
}
My PHP:
<?php
$email = true
if ($email == true) {
echo "taken";
}
?>
But, when I just put:
echo "taken";
The AJAX and JQUERY works exactly how it should and the respective error message pops up. "taken" is being echo'd either way, so I don't get what is going on. What could I be doing wrong?
You're missing your semicolon.
$email = true
needs to be
$email = true;
In your response, you will probably be getting a PHP error - unless your error messages are suppressed.
I'm trying a login in a lightbox via jquery and ajax.
My goal is that after the user logs in successful, he gets redirected to a special site.
The login via jQuery.ajax works fine, but I would like that in case the user is logged in he gets redirected, in case he's not logged in he stays on the login site.
Here's my code so far:
$(".logmein").click(function() {
var username = $("input#username").val();
var password = $("input#password").val();
var dataString = 'username='+ username + '&password=' + password + '&login=Login' ;
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
data: dataString,
success: function() {
window.location = "http://test.home/kundenbereich.html";
$('#login_form').html("<div id='message'>Superb</div>");
}
});
return false;
});
The ajax request is performed successfully but, can I generate a callback from php to inform js that the user is not logged in, and then not redirect him via "window.location"?
In this case he gets redirected anyway, no matter if the login in php was successful or not!
The login function is on the same page(php) and is working with username and password.
It would be great to get some help on this issue.
Sincerely.
Make your php login function return a json object for instance:
// login.php page :
[...]
if (some_auth_system_log_user_in($username, $password)) {
exit(json_encode(array('result'=>'success', 'message'=>'Logged in successfully!')));
} else {
exit(json_encode(array('result'=>'error', 'message'=>'Some error')));
}
Then the jquery code would be:
var username = $("input#username").val();
var password = $("input#password").val();
$.post('login.php', {username:username, password:password}, function(response){
if (response.result == 'success') {
// redirect
} else {
// do something with response.message here
}
}, 'json');
Using json gives you the ability to post back multiple params, or translated messages, etc, so in general is better than just echo true/false in your php file
PHP:
if (Fe_User::Login($this->getPost('username'), $this->getPost('password'))){
echo "true";
}
else{
echo "false";
}
Script :
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
data: dataString,
success: function(response) {
if(response == "true"){
$('#login_form').html("<div id='message'>Superb</div>");
window.location = "http://test.home/kundenbereich.html";
}
}
});
It worked when i putted the output at the start of the php file and let it die(); after outputting the ajax value.
It didnt worked out because i use the same document for the ajax output, therefore the response was the whole Markup of the page.
Thanks for your help
I've created a JQuery script that checks a database for usernames and shows an error if you type in an existing name on keyup, this is workng fine but the form still submits even if this error is true. What other code can I add to check that this error doesn't exist? Here is the code I have so far:
<script>
$(function()
{
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Thank you
please see the comments on the code
assuming that the data == 1 means that the name is already registered and you will show an error
<script>
$(function()
{
var name = false; // a variable that holds false as the initial value
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
name = true; // on success , if the name isnt there then assign it to true
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username) && name == true) // check for the value of name
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Instead of checking the username against the regex, you should check the status of $('.usernameStatus') because it is possible that it passes the regex test but still fails the duplicate test returned from your db.
So
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
should instead be:
$('#registerButton').click(function()
{
var username=$("#username").val();
if(!$('.usernameStatus').hasClass('error'))
{
Even better would be to introduce a variable that holds the validity of the name field so you don't need to get the DOM Element all the time and check it's class.
I think your error might be because of a bad data syntax
It should be like this:
data: 'username:'+ username,
Debug your PHP code to see if its receiving the username properly at the moment though