I have a problem and a question for the code below.
The code below performs a live check if username already exists in database. Now when I enter username manually it all works fine with giving live success or error message as the case is but when after typing 1 or 2 characters I choose username from autofill options given by browser It doesn't give any success or error message instead keeps showing Enter 3 to 11 characters which is initial message for username requirements. Can't figure out why it doesn't work when username is selected from autofill options.
index.php
<script type="text/javascript">
$(document).ready(function(){
$('#un').keyup(function(){
var username = $(this).val();
var Result = $('#result');
if(username.length > 2 || username.length > 11) { // if greater than 2 (minimum 3)
Result.html('./img/loadgreen.gif');
var dataPass = 'action=availability&username='+username;
$.ajax({ // Send the username val to available.php
type : 'POST',
data : dataPass,
url : 'available.php',
success: function(responseText){ // Get the result
if(responseText == 0){
Result.html('<span class="success">Available</span>');
}
else if(responseText > 0){
Result.html('<span class="error">Unavailable</span>');
}
else{
alert('Problem with sql query');
}
}
});
}else{
Result.html('Enter 3 to 11 characters');
}
if(username.length == 0) {
Result.html('');
}
});
});
</script>
<table>
<tr>
<td>
<input type="text" name="username" id="un" placeholder="Username" class="username" />
</td>
<td class="result" id="result"></td>
</tr>
</table>
available.php
<?php
include ( "./inc/connect.php" );
if(isset($_POST['action']) && $_POST['action'] == 'availability')
{
$username = $_POST['username'];
$que=$db->prepare("SELECT username FROM users WHERE username=:username");
$que->execute(array(':username'=>$username));
$count = $que->rowCount();
echo $count;
}
?>
Now my question is how to secure POST on available.php lot of people tell you need to sanitize or escape every POST and GET data. So what works best with PDO. Also heard escaping doesn't works with PDO may be I am wrong?
try jquery .change() instead of .keyup()
Related
I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.
I'm creating a system that checks (via AJAX) if a given username is already taken. If so, then it alerts the user accordingly. I'm basing my system off of this tutorial and have tried adapting it to my site.
$(document).ready(function()//When the dom is ready
{
$("#username").change(function()
{ //if theres a change in the username textbox
var username = $("#username").val();//Get the value in the username textbox
if(username.length > 3)//if the lenght greater than 3 characters
{
$("#availability_status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
//Add a loading image in the span id="availability_status"
$.ajax({ //Make the Ajax Request
type: "POST",
url: "ajax_check_username.php", //file name
data: "username="+ username, //data
success: function(server_response){
$("#availability_status").ajaxComplete(function(event, request){
if(server_response == '0')//if ajax_check_username.php return value "0"
{
$("#availability_status").html('<img src="available.png" align="absmiddle"> <font color="Green"> Available </font> ');
//add this image to the span with id "availability_status"
}
else if(server_response == '1')//if it returns "1"
{
$("#availability_status").html('<img src="not_available.png" align="absmiddle"> <font color="red">Not Available </font>');
}
});
}
});
}
else
{
$("#availability_status").html('<font color="#cc0000">Username too short</font>');
//if in case the username is less than or equal 3 characters only
}
return false;
});
});
ajax_check_username.php - HERE's where I think I'm having problems!!
<?php
include ("inc/db/db.php");
if($stmt = $mysqli->prepare('SELECT NULL FROM `bruger` WHERE `brugernavn` = ?'))
{
$stmt->bind_param('s', $brugernavn);
$brugernavn = $_POST["brugernavn"];
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if($count = 0)
{
echo '1';
}
else
{
echo '2';
}
}
?>
<tr>
<td><p>Brugernavn</p></td>
<td><input type="text" name="brugernavn" id="username"></td>
<td><span id="availability_status"></span></td>
</tr>
ATTENTION
I think I've made mistakes in my php, so it may be why it does not bother to do what I want it .. but it's just when I think.
This is what my html looking for when I need to check user name in the database. this is how I get no errors at all. it must be said that I never play with ajax or javascript before. so it will be a great help if you could help me further.
Feel free to ask if there is more you want to know something.
This if($count = 0) should be if($count == 0) if that affects your logic.
You're assigning $brugernavn after you're using it.
$stmt->bind_param('s', $brugernavn);
$brugernavn = $_POST["brugernavn"];
Using ajaxComplete is not useful here:
$("#availability_status").ajaxComplete(function(event, request){
You are assigning where you should be comparing:
if($count = 0)
Your Javascript expects a 0 or 1, but your PHP script outputs one of 1 or 2.
I have a code in which there's a function which is supposed to check if a username is available or not.
I'm confused about how this function works.
JS:
jQuery(document).ready(function(){
// binds form submission and fields to the validation engine
jQuery("#register-form").validationEngine();
});
HTML input:
<form action="" id="register-form">
<input value="" class="validate[required,custom[onlyLetterNumber],maxSize[20],ajax[ajaxNameCallPhp]]] input" type="text" name="username"/>
</form>
This is my JS function:
(function($){
$.fn.validationEngineLanguage = function(){};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"ajaxNameCallPhp": {
// remote json service location
"url": "ajaxNameCallPhp.php",
// error
"alertText": "* This name is already taken",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
and this is my ajaxNameCallPhp.php function:
include ("config.php");
$username = trim(strtolower($_POST['username']));
$username = mysql_escape_string($username);
$query = "SELECT username FROM user WHERE username = '$username' LIMIT 1";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo $num;
mysql_close();
So anyone can give me a solutions ?
I appreciate and thanks with your attention.
Thank you.
try this
function UserNameExist(){
$("#msg").html( "* Validating, please wait" );
$.ajax({
url: "ajaxNameCallPhp.php",
type: "POST",
data: {username : $('#username').val()},
dataType: "html"
}).done(function(msg) {
if(msg > 0){
$("#msg").html( "* This name is available" );
}else{
$("#msg").html( "* This name is already taken" );
}
});
}
where #msg is the id of the div where you show your massage
and #userName is the id of the text box
hope that help.
I'm trying to authenticate a user using AJAX wrapped with jQuery to call a PHP script that queries a MySQL database. I'm NOT familiar with any of those technologies but I (sorta) managed to get them working individually, but I can't get the jQuery, AJAX and HTML to work properly.
[Edit:] I followed Trinh Hoang Nhu's advice and added a return false; statement to disable the Submit button. All previous errors fixed, I can't get the object returned by the AJAX right.
HTML
Here's the HTML snippet I use:
<form id="form" method='post'>
<label>Username:</label>
<input id="user" name="user" type="text" maxlength="30" required /> <br />
<label>Password:</label>
<input id="pass" name="pass" type="password" maxlength="30" required /> <br />
<input id="url" name="url" type="text" value="<?php echo $_GET['url'] ?>" hidden />
<input name="submit" type="submit" value="I'm done">
</form>
jQuery/AJAX
Here's my jquery code for using AJAX to authenticate a user (sorry if the indenting is messed up because of the tabs):
function changeMessage(message) {
document.getElementById("message").innerHTML = message; }
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass: $("#pass").val(), url: $("#url") },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val(""); }
//if authenticated
else {
changeMessage("Authenticated");
window.location.href = result; }
} );
//to disable the submit button
return false;
} );
} )
PHP
And here's my PHP script that gets called:
<?php
ob_start();
session_start();
$user = $_POST['user'];
$pass = md5($_POST['pass']);
mysql_connect('localhost', 'root', '');
mysql_select_db('stufftothink');
$query = "select * from users where user = '$user' and pass = '$pass'";
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_array($result)) {
$i = 1; }
if ($i == 1) {
$_SESSION['user'] = $user;
$invalid_urls = array('register.php', 'login.php');
$url = $_REQUEST['url']; //not sure whether _GET or _POST
if (in_array($url, $invalid_urls)) {
echo '/stufftothink/profile.php'; }
else {
echo '/stufftothink/'.$url; }
}
else {
echo 'false'; }
mysql_close();
?>
Edit
I've been getting a lot of downvotes on this question. I had accidentally submitted the question without the explanation filled in. I went back to edit it, but when I came back, there were already 4 downvotes. It had barely been a couple of minutes. Am I doing something wrong, or were the first 5 minutes the problem?
First if you want to submit form using ajax, you must return false from your submit function. Otherwise your browser will handle it and redirect you to another page.
If you want to return an object from PHP, you must convert it to json using json_encode,
for example:
//PHP
$return = array("url" => "http://www.google.com");
echo json_encode($return);
//would echo something like {"url":"http://www.google.com"}
//JS
$.post(url, data, function(data){
alert(data.url);
});
You have no ending ;'s on functions.
Should be:
function changeMessage(message) {
document.getElementById("message").innerHTML = message;
};
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass:$("#pass").val() },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val("");
}
//if authenticated
else {
changeMessage("Authenticatred");
window.location.href = "/stufftothink/" + result;
}
});
});
});
Not sure if that'll fix it, but it's the only thing that jumps out at me.
Code Logic:
1) User types in username and password, user clicks submit.
2) jQuery script pulls the php script below.
3) jQuery determines which php value is returned.
4) if value 1 is returned, jquery and php will process what's in the if statement.
5) if value 0 is returned, jquery and php will process whats in the else statement.
How do I successfully make the code below work alongside the logic above? I can't seem to make a connection in my mind.
class1.php
$email = mysql_real_escape_string(strip_tags($_POST["username"]));
$password = sha1($_POST["password"]);
$sql = "SELECT * FROM users WHERE username = '{$email}' AND password = '{$password}'";
$result = mysql_query($sql) or exit("ERROR: " . mysql_error() . "<br>IN QUERY: " . $sql);
if (mysql_num_rows($result) > 0) {
return 1;
$row = mysql_fetch_array($result);
$_SESSION["userid"] = $row['user_pid'];
} else {
return 0;
$userid_generator = uniqid(rand(), false);
mysql_query("INSERT INTO users (user_pid, email, password, datetime_registered, is_leader) VALUES ('$userid_generator', '{$email}', '{$password}', NOW(), 'no')");
$id = mysql_insert_id();
$leaders = mysql_query("SELECT * FROM users WHERE is_leader LIKE '%yes%'");
while($rows = mysql_fetch_array($leaders)) {
if ($rows['is_leader'] == 'yes') {
$leader_id = $rows['user_pid'];
mysql_query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type)
VALUES('$leader_id', '$userid_generator', NOW(), 'full')");
echo "new user created and logged in";
}
$_SESSION["userid"] = $userid_generator;
}
}
?>
index.html:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.loading {
float:right;
background:url(img/ajax-loader.gif) no-repeat 1px;
height:28px;
width:28px;
display:none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var username = $('input[username=username]');
var password = $('input[password=password]');
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "processing/class1.php",
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
alert('success');
//if process.php returned 0/false (send mail failed)
} else { alert('failure');
}
});
return false;
});
});
</script>
<input type="text" id="username" name="username" />
<input type="password" id="password" name="password" />
<input type="submit" id="submit" />
<div class="loading"></div>
<div id="display"></div>
Ajax is effectively a "blind client". So, think of what you would see if you were to manually view the php script, and interpret that as what your ajax callback would be parsing.
Having said that, the "0/1" return you're looking for is dependent on one (of many) echos going on in your script (most notably the following):
echo "new user created and logged in";
if you want the ajax callback to recognize a 0/1, this would need to only echo a "1" (not verbiage), where as errors would simply return a "0" (such as your or exit("ERROR...).
EDIT
Also, looking further, your var data = 'name=' component (assuming you want it to align with the PHP $_POST["username"]) should probably be renamed to var data ='username=' (the data property of the ajax call is what' populating your PHP's $_POST variables, so names need to align).