Ajax Validate username and password - javascript

I need help! I have this code that work very good to validate username in mysql database using Ajax, php and Javascript but when I try to add for validate the password too not work and I have been test all possible ways in my mind!
-- Code in html page to validate username
function admin_search(){
$("#checkuser").click(function(){
var user_name = $('#admin_user').val();
if(user_name == ""){
$("#disp").html("");
}
else{
$.ajax({
type: "POST",
url: "checklogin_admin.php",
data: "user_name="+ user_name ,
success: function(html){
$("#disp").html(html);
}
})
return false;
}
})
}
-- Code in checklogin_admin.php
if(isset($_POST['user_name'])) {
$user_admin = mysql_real_escape_string($_POST['user_name']);
$query = mysql_query("SELECT * FROM $tbl_name WHERE user='$user_admin'");
$row = mysql_num_rows($query);
if($row == 0) {
echo "<span style='color:red;'>NOT EXIST</span>";
} else
{
echo "<span style='color:green;' id='exist'>EXIST</span>";
}
Im tying to add for validate the password too with this:
function admin_search(){
$("#checkuser").click(function(){
var user_name = $('#admin_user').val();
var user_pass = $('#admin_pass').val();
if((user_name == "") & (user_pass == "")){
$("#disp").html("");
}
else{
$.ajax({
type: "POST",
url: "checklogin_admin.php",
data: "user_name="+ user_name
"user_pass="+ user_pass,
success: function(html){
$("#disp").html(html);
}
})
return false;
}
})
}
But, nothing works!

Data should send a single structure ...
data: { "user_name": user_name,
"user_pass": user_pass },
... you could also do something like this ...
data: "user_name=" + user_name + "&" + "user_pass=" + user_pass,
I personally would recommend the first method ...
In both, be careful of sending the username and password in the clear as part of the URL.
You'll have to adjust the backend PHP to account for the data being sent.

Related

Check any data after confirmation message using JSON

I want to make the data alert successfully saved or fail after the user selects on the confirmation message. In this case data checking occurs after the user confirms the message I made.
This is my Javascript Code :
$('#add-btn').on('click', function(event){
var confirmation = confirm("Do you want to save ?");
if (confirmation == true) {
var code = $('#code').val();
var name = $('#name').val();
var unit = $('#unit').val();
var price_code = $('#price_code').val();
var type = $('#type').val();
var final = $('#final').val();
var dataString = 'code=' +code+ '&unit=' +unit+ '&price_code=' +price_code+ '&type=' +type;
if (code != '' && name != '' && unit != '' && price_code != '' && type != '' && final != ''){
event.preventDefault();
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.status == 'success'){
alert("Success !");
}
else if(data.status == 'error'){
alert("Data already used !");
}
}
});
}
else{
alert('Please fill all fields !');
}
}
});
All input success to save but the alert cannot show.
I think problem in your php file. your JOSN data is not in correct format that you received in success.Please try this in your add_data.php file
//All code goes here and after insert try this
$array = array();
if(if data insert successfully) {
$array['status '] = 'success';
} else {
$array['status '] = 'error';
}
header('Content-Type: application/json');
echo json_encode($array);
The success function is only executed if everything went well. If there has been any error, you need to add the Ajax failure function as follows:
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
alert("Success !");
}
}).fail(function () {
alert("Data already used !");
});
finally I find my solution. I'm sorry for my carelessness.
That happened because my variable dataString did not complete.
It should be :
var dataString = 'code=' +code+ '&name=' +name+ '&unit=' +unit+
'&price_code=' +price_code+ '&type=' +type+ '&final=' +final;
Thank you all for your kindness :-)

PHP GET variable not being set

I have a registraion php class that displays a form and when the registration button is clicked, calls a function in a login javascript file. This file uses ajax to post data to a index.php file. My index.php file cannot access this data, despite the post being a success (ajax success is true as the alert is being called).
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val();
urlPath = "../index.php?action=register";
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
})
}
index.php
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
if(isset($_GET['action'])) {
if($_GET['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}
?>
You used POST method of ajax. So send data also in POST manner like below:-
// Send the login/registration data to database
$(document).ready(function() {
var username = $("#usernameField").val();
var email = $("#emailField").val();
var password = $("#passwordField").val();
$.ajax({
type: "POST",
url: "../index.php",
data: {"username":username,"email":email,"password":password,"action":"register"},
success: function (result) {
alert(result);//check the change
}
});
});
And then change GET to POST at php end:-
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
//single condition can do the job and use POST instead of GET
if(isset($_POST['action']) && $_POST['action'] == "register" ) {
echo "hello"; //check the change
}
?>
Note:- Please take care of comments too.(added in the code)
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
});
Try adding the action also in post data and receive it as $_POST
if($_POST['action']) {
if($_POST['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}

JqueryAjax and php logic

Hey guys im with a problem getting a value from php. I know we have a lot of problems with this kind of issues, but i need help.
This is my javascript
$( document ).ready(function() {
$(".loading_bg").hide();
});
$( document ).ajaxStart(function() {
$(".loading_bg").fadeIn("slow");
});
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
and this is my php
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_POST['function'])) {
$user = $_POST['username'];
$password = $_POST['password'];
echo login::validate_user($user, $password);
}
class login {
static function validate_user($username, $password) {
//Call a new default connection
$db = db::connect();
//Prepare our sql
$stmt = $db->prepare("SELECT * FROM Accounts WHERE username = :username AND password = :password");
//Bind our values to the SQL statement
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->bindValue(':password', $password, PDO::PARAM_STR);
$stmt->execute();
//Get number of affected rows
$results = $stmt->rowCount();
//If to check if we can find any row with username and password
if($results === 1) {
//return json_encode("valid account");
} else {
return json_encode($username);
}
}
}
?>
When i do the request im getting a undifned error from my var, i dont know how to fix it, can someone help me, if possible.
I think its something with my $_POST.. because if run the php with login::validate_user("teste","teste); i can get the json result..
Everything else is fine, you are not passing data correctly to ajax call. You are making query string but you have to pass JSON object if you want to capture it in $_POST in php and can append to url if you want to capture in $_GET array. I have corrected your function in both ways below:
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = { 'function': 'validate_user', 'username': username, 'password': password }
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
When you want to capture data in $_GET at server side
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php?' + datastring,
data: {},
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
Here is PHP Code
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_GET['function'])) {
$user = $_GET['username'];
$password = $_GET['password'];
echo login::validate_user($user, $password);
}
.... // Remaining Class will come here
Im sorry to bother all of you, the real problem its my form input feilds.. i forgot to set a class... Thank you all, and once again, im sorry to make you lose time with such a silly problem.

How to use jQuery/Ajax to perform MySQL Query

I'm trying to use jQuery to check if the username that the user entered in a form is already taken. Below are the relevant codesnippets in Java, and existence.php.
*javascript*
var username = document.register.username.value;
usernameTaken = checkUserExistence(username, 'username');
function checkUserExistence(str, type){
var dataString = '?str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existence.php",
data: dataString,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
$("#submit").val('Succes!');
return 1;
}else{
$("#submit").val('Failure!');
return 0;
}
}
});
}
return false;
}
*/JavaScript*
<?php
include("inc/connect.php");
$data = $_POST["str"];
$type = $_POST["type"];
switch($type){
case "username":
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
break;
}
?>
What am I doing wrong?
My website is supposed to show live hints to the users, like 'your username is too short' etc. All hints are working, but the ones where it should say 'your username is already taken' won't show. The form gets processed to my PHP-register function, where usernames that are already taken get rejected, so somehow the checkUserExistence-function and the existence.php page are not working.
Edit:
For a live demonstration of my code, go to:
http://beta.somentus.nl/index.php
The usernames 'Admin', 'Somentus' and 'Rik' are already taken, try them out :)
$data = $_POST["data"];
should be:
$data = $_POST["str"];

Passing data in ajax JQUERY

I'm creating a Login page with ajax and JQuery.
Here is my code for ajax:
<script>
$(document).ready(function() {
$('#login').click(function(){
var username=$("#username").val();
var password=$("#password").val();
var url = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: url,
cache: false,
success: function(responceText){
document.write(responceText);
if(responceText==1){
document.write('____Welcome____');
}
else if(responceText==0){
document.write('____Login Failed____');
}
else if(responceText == -1){
document.write('____Some Thing went wrong____');
}
}
});
}
return false;
});
});
</script>
And here is the ajaxLogin class:
<?php
include("db.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password'])){
$username=mysqli_real_escape_string($db,$_POST['username']);
$password=md5(mysqli_real_escape_string($db,$_POST['password']));
$result=mysqli_query($db,"SELECT user_id FROM users WHERE user_name='$username' and user_pass='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if($count==1) echo 1;
else echo 0;
}
else{
echo -1;
}
?>
I've debugged the code and i thing the url which i'm passing to the ajax login is not working fine. The values for username and password are null when i load ajaxLogin.php. What is the problem with my url?
var url = 'username='+username+'&password='+password;
is responceText integer ? are you sure about it ? you can try like
success: function(responceText){
responceText = parseInt(responceText);
document.write(responceText);
also... you can pass values in better way by construct it as an object...
var url = {
'username': username,
'password': password
}
Your url contains data for GET method. For POST you need to pass data like this:
data: {username: username, password: password}

Categories

Resources