Using Javascript to run a php script to check username - javascript

I've been trying to build a registeration form for a website I am building. I can do the basics but I want it to check the username availability without reloading the page.
JAVASCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
var username = $("#Username").val();
$.post("scripts/check_username.php", {username: username}, function(data)
{
if(data == 'false')
{
alert('Username not available');
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
HTML
<form id="registerForm">
<table>
<tr><td>Username</td><td><input id="Username" class='textInput' type='text' name='username' required></td></tr>
PHP SCRIPT
<?php
include 'open_connection.php';
$result = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$result = 'false';
}
echo $result;
?>
When I leave the textbox it says username available no matter what. I placed a username "test" in the database... no luck
Please help

PHP:
$output = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$output = 'false';
}
echo $output;
Ans Script:
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
$.post("scripts/check_username.php", {username: $("#Username").val()}, function(data)
{
if(data =='false')
{
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
By the way, don't use mysql_* function, they're deprecated. use Mysqli or PDO. Next thing is you forgot to put semi-colon that the end of your statements !

You specify $("#Username").value do you mean to use $("#Username").val()?
$('#Username').value is probably returning you rubbish which will not exist in your DB.

Do you use Developer Tools or Firebug?
It would be easy to see where the issue lies if you examined the $.post to check_username.php:
(1) is the correct post request being sent? I think your data object should be {"username":username}
(2) is your script responding true? or something else? You only know it's not returning false by the way your if statement is structured.

Related

Passing js variable to php using ajax does not work

I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js

[Ajax][PHP] - login form, response is always empty

I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.

Ajax success object

I'm trying to validate the form using AJAX. This is what I've done so far:
$('#login-form').submit(function(e) {
e.preventDefault();
var user = username.value;
var pass = password.value;
if (user != '' && pass != '') {
$('#login').html('Proccessing...');
$.ajax({
url: 'login.php',
type: 'POST',
data: {
username: user,
password: pass
},
processData: false,
contentType: false,
success: function(response) {
if (response == 'success') {
window.location.href = 'admin.php';
} else {
$('.login_message').html('Incorrect Credentails');
$('#login').html('Login');
}
}
});
} else {
$('.login_message').html('Fill All Fields');
$('#login').html('Login');
}
})
and it seems like response doesn't return success. Below is the login.php file
<?php
session_start();
$password = $username = '';
$_SESSION['user'] = $_SESSION['error'] = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['login'])) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
echo 'username: ' . $username . ' and ' . ' password: ' . $password;
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
;
$_SESSION['user'] = $username;
header('Location: admin.php');
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
} else {
echo mysql_error();
}
}
}
?>
If it happens you have found the solution, please explain to me how you find the solution and what I've done wrong.
Thank you in advance.
Since this is ajax request,we need to send some response from server. As you did in your question check if(response=='success'). To do that, you need to send success to your client. If everything is ok (data send to server and query) then in your login.php edit this line
if($password == $dbpass) {
$_SESSION['user'] = $username;
//comment this line
//header('Location: admin.php');
echo "success";
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
Here I put one line code echo "success"; and I believe this will resolve your issue.
Returning values from PHP back to JS
When using AJAX, I believe if you do echo in the PHP target file (here login.php) it will act as a return. Therefore the code after a echo will not run as you might expect.
Also in your code you have: echo $_SESSION['error'] = '';
Use == to compare two object, = is the assignment operator.
Retrieving AJAX data in PHP file
The use of the ajax() method from jQuery in your code looks correct to me. So when the call is made the information is sent asynchronously to the server. More precisely it will send the parameters to the PHP file you've specified in the ajax object properties: login.php.
In login.php you can access your passed parameters in the $_POST array.
You would have the following:
$username = $_POST['username'];
$password = $_POST['password'];
// process information...
$state = 'success'
// now you can return a JSON object back to your page
// I strongly recommend using a PHP array and converting it to JSON
// this way it's very easy to access it back with JS
$response = array(state=$state)
echo json_encode($response);
And back in your jQuery code you access the state value with response.state
if(response.state == 'success') {
alert('It is a succcess!');
}
Debugging PHP target files
Now you generally have problems in the code in this PHP files. And it's not an easy thing to debug it. So the way I proceed is: I set the parameters in stone in login.php for instance:
$username = 'usernameTest'; // $username = $_POST['username'];
$password = 'passwordTest'; // $password = $_POST['password'];
Then I would open the PHP file in a browser and run it do see if it echoes the object and if there are any bugs.
Then you can put back $username = $_POST['username']; and $password = $_POST['password'];.
Actual code
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
$state = 'success';
} else {
$state = 'failed';
}
} else {
echo mysql_error();
}
}
Warning mysql(), md5() and SQL injections
Don't use the deprecated and insecure mysql_* functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.
You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Using strip_tags() is far from a safe way to escape data.
Don't use md5() for password hashing. It's very insecure. Use PHP's password_hash() and password_verify() instead. If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality.
- Magnus Eriksson

from PHP to Javascript to enter PHP again and set Sessions

Im trying to fix this issue im having. The problem is that I use this code when someone want to sign in to the admin panel:
<script>
function myFunction() {
//alert('you can type now, end with enter');
$("#test").focus();
}
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
// alert($("#test").val());
var email = $("#test").val();
if(email==''){
// alert("Error.");
sweetAlert("Oops...", "Error!", "error");
} else {
$.post("sess.php",{ code1: code},
function(data) {
// alert(data);
// swal(data);
if((data)=="1") {
swal("Welcome!", "Please wait!", "success")
} else {
sweetAlert("Oops...", "Something went wrong.", "error");
}
$('#form')[0].reset(); //To reset form fields
});
}
});
});
</script>
Sess.php looks like this:
<?php
include("conn.php");
?>
<?php
include("ipcheck.php");
$code2=htmlEntities($_POST['code1'], ENT_QUOTES);
$info = explode("-", $code2);
$username = $info[0];
$password = $info[1];
$_POST = db_escape($_POST);
$sql = "SELECT id FROM adminusers
WHERE user='{$username}'
AND pass='$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0){
echo "2";
exit;
}
// Session for user
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
// DAtabse going on here.
echo "1";
exit;
?>
So if the username and password is correct the login is successful and those session is set in sess.php:
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
My problem is, how do I get the sessions that is set for the user thru sess.php back to index.php using javascript so I can set the sessions in index.php not in sess.php?
why to you care to pass the session to javascript ? I mean if you set the session server side on sess.php you have already setted it even in index.php (session exists during the entire ... session :-) ) so when sess.php return that the authentication is correct, your javascript should just move the page to index.php like:
window.location.href = 'index.php';
in index.php, if you print the session print_r($_SESSION) you should see the values that you have previously set in sess.php
If your $_SESSION is empty in index.php probably you have to start the session before reading $_SESSION using session_start();

AJAX not returning a variable from php

I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>
the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.

Categories