How to: Ajax check values in php/database - php

How to POST values from submit and check if they exist in mysql?
And what do I have to type in my .php file?
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$('#login').submit(function(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
});
}
function getData(sendData) {
$.ajax({
type: 'POST',
url: 'http://www.url.php',
data: { 'username': username, 'password': password },
success: afhandeling,
});
}

Call ajax like this:
jQuery.ajax({
type: "POST",
url: "http://www.url.php",
data: { username:username,password:password },
success: function( data )
{
}
});
and in ajax file:
if (isset($_POST['username']) && isset($_Post['password']))
{
$query = "SELECT * FROM users WHERE username='".$_POST['username']."' AND password=".$_POST['password'];
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row)
{
echo 'login';
}
else
{
echo "error";
}
}

I think the URL has to be a local one, i.e. "/projects/blindchat/login.php".
On that page you can write something like this:
if (isset($_POST['username']) && isset($_POST['password'])) {
// MYSQL query:
SELECT 1 FROM users WHERE username = ? AND password = ?
}
Remember you have to escape the variables first to prevent SQL injection.

In login.php page you need to do something like this:
if(isset($_POST['username']) && isset($_Post['password'])) {
$q = "SELECT * FROM users WHERE username=$_POST['username'] AND password=$_POST['password']"
$r = mysql_query($q);
if(mysql_num_rows($r)==1) //Do Login
else echo "ERROR";
}

You submit the form which launches your ajax script that sends the data over to your PHP file that handles the input and gives you an answer.
Use PDO or MySqLi. Mysql is depreceated and no longer supported. My example below uses the PDO method.
Your PHP should look something like this(this is untested code, so there might be typos):
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
// We create a PDO connection to our database
$con = new PDO("mysql:host=yourhost;dbname=yourdatabase", "username", "password");
// We prepare our query, this effectively prevents sql injection
$query = $con->prepare("SELECT * FROM table WHERE username=:username AND password=:password LIMIT 1");
// We bind our $_POST values to the placeholders in our query
$query->bindValue(":username", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
// We execute our query
$query->execute();
$result = $query->fetch(); // Grab the matches our query produced
// Here we check if we found a match in our DB
if (!empty($result)) {
echo "Matches were found";
} else {
echo "No matches found";
}
} else {
echo "Please fill out all fields";
}
?>
As for getting a reply from your AJAX script you can simply alert the response or show it as you please.
success: function(data) {
alert(data);
}

Related

jQuery AJAX how to pass PHP echo to success parameter

So I was learning ajax and followed some codes I found online but didn't know how to pass the value from the PHP.
so this is my email.php
$conn = mysqli_connect($servername, $username, $password, $db);
$email = $_POST['email'];
$query = "SELECT * FROM registration WHERE email = '$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if ($count == 0) {
$data = json_encode(0);
} else {
$data= json_encode(1);
}
mysqli_close($conn);
return data;
and this is my ajax
$.ajax({
url: "email",
type: "POST",
data: {
email: email,
},
cache: false,
success: function(data) {
alert("data: " + data); // I tried this one to check what is in data but it's not the values from the echo in PHP
if (data == 0) {
$('#message').html('available');
} else if (data == 1) {
$('#message').html('not available');
}
}
});
Your help would be much appreciated! Thank you!
[!] EDIT [!]
Sorry my problem was different. I have a template.php file for the whole HTML and where all my PHP files are included. here is the part:
if (isset($_GET["route"])) {
if ($_GET["route"] == 'home' || $_GET["route"] == 'email' ||) {
include "modules/".$_GET["route"].".php";
}
}
now the value in alert(data) is the whole thing in the template.php and the 0 or 1 at the end. what I did to solve this problem is: data.slice(-1) lol not a good practice though. so if u have other solutions, I would really appreciate it. thank you!
You have to make changes to the PHP file
$data = json_encode(0);
Then return the encoded data in your PHP file like this:
return $data;
So whenever you make a request to the file it will have a return type that can be accessed in ajax.
You don't have to encode the number. Just pass the number as a string to the echo statement.
$conn = mysqli_connect($servername, $username, $password, $db);
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query = "SELECT * FROM registration WHERE email = '$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if($count==0){
echo "0";
} else{
echo "1";
}
mysqli_close($conn);
} else {
echo "1";
}

Trying to see if an email is not a duplicate

I've tried to verify if an email already exists in the database.
The same system worked perfectly if I tried to verify a username.
I'm using AJAX and PHP.
This is the file that gets the $_POST variables.
<?php
require_once 'Config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
if (!empty($password) and !empty($email)) {
$notEmpty = true;
include 'validate.php';
if($notEmpty == true and validateEmail($email) == true){
$password = md5($password);
$stmt = $link->prepare("INSERT INTO `Users`(`user_password`, `user_email`) VALUES (?,?)");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
}
}else{
$notEmpty == false;
}
}
?>
and this is the file that verifies the email doesn't exist on the database.
function validateEmail($user_email){
include '../Backend/Config.php';
$sql = "SELECT `user_password`, `user_email` FROM `Users` WHERE `user_email` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s",$user_email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
echo 1;
return false;
}
else{
// echo json_encode(array('status' => 'OK'));
echo 0;
return true;
}
}
Js code(ajax):
$('#form').submit(function(e) {
//Don't refresh the page
e.preventDefault();
//Collecting data for the server call
post_data = {
'email' : $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
//AJAX server call to signup.php,which calls validate.php
$.ajax({
method: "POST",
url: "../Backend/signup.php",
data: post_data
})
//Server response and setting the input values to ""
.then(function( msg ) {
if(msg == 0){
console.log("Success, user data inserted. Code: " + msg);
}
//Failed
if(msg == 1){
console.log("Inserting failed. Error code:" + msg);
document.getElementById("error").innerHTML = "This email already exists.";
}
$('input[name=email]').val("");
$('input[name=password]').val("");
});
});
It inserts it anyway, what is the problem here?
If you immediately call num_rows() after executing a prepared statement, it will usually return 0 as it has no way to know how many rows are in the result set, since the result set is not saved in memory yet. You must first call store_result() to buffer the results so that the subsequent call to num_rows() will contain the correct results.
This is explained in the "User Notes" section at the bottom of the PHP documentation for num_rows().

Why does my AJAX request print out the pages entire HTML code?

I'm trying to make an AJAX request, send the data to a PHP file, check if the username and password are correct, return an answer, and then run the login.php file which determines runs the session.
Right now, my AJAX request does nothing except print out my entire HTML code for the login page.
If someone knows why, please let me know...
(I apologize in advance for posting all of my login.js and checkLogin.php, I fear that the question may be unanswerable without the context for both)
This is login.js
$(function() { //Once the document has fully loaded
$("#login_form").submit(function(event) {
//INITIALIZING VARIABLES
var userName = $("#userName").val();
var passWord = $("#passWord").val();
var error = 0;
event.preventDefault(); //Prevent normal submit action
$("#userError, #passError").text(""); //Clear the text each time the user clicks submit
if (userName == "") { //Checking if the username is blank
$("#userError").text("Please enter your username");
error = 1;
}
if (passWord == "") { //Checking if the password is blank
$("#passError").text("Please enter your password");
error = 1;
}
//BEGIN Ajax Request
var $form = $(this),
term = $form.find("userName, passWord"),
url = 'checkLogin.php';
var posting = $.post(url, {username: userName, password: passWord});
posting.done(function(data) {
$("#userError").text(posting.responseText);
});
//END Ajax Request
if (error == 0) {
$("passError").text("Success");
}
}); //END submit button click
$("#login_form").submit();
});
This is checkLogin.php
<?php
$link = mysqli_connect(DB info private); //Database Connection
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //Keeps the text inside the this.responseText
//Preparing and Binding SQL statement
$stmt = mysqli_prepare($link, "SELECT username, password FROM login WHERE username =? and password =?");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
//PRINTS UNIDENTIFIED INDEX
$username = $_POST['username']; //Retrieving the username
$password = $_POST['password']; //Retrieving the password
mysqli_stmt_execute($stmt); //Execute the parameterized prepared statement
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
}
?>
Form tag from client_login.php
<form action="login.php" method="post" name="login_form" id="login_form">
</form>
You are not returning anything on checkLogin.php. You should try:
$row = mysqli_fetch_assoc($result);
if($row) {
echo "User found!";
exit();
}
I would recommend you, returning a text in json format. This way you can return more complex reponses to use in your js script. For example, in your checkLogin.php:
$row = mysqli_fetch_assoc($result);
if($row) {
echo json_encode([
'code' => '1', // code that represent successful
'message' => 'User found!'
]);
exit();
}
And in your login.js:
posting.done(function(data) {
var response = JSON.parse(data);
if(response.code == '1') {
$("#userError").text(response.message);
}
});
There are few issues here
url = checkLogin.php; should be url = 'checkLogin.php';
Right now url will be undefined and ajax url will post everything to yoursite.com/undefined and obiviosly the server will return 404 with default 404 page. Thats why you see html in your response.
YourcheckLogin.php should return some data to client. Use echo() for that.

Returning a variable from PHP to AJAX

how can I return a variable from a PHP query to AJAXA. I want the user to be redirected to the user panel using javascript after successfully entering the login and password. The query in PHP was successfully written but Ajax does not return any results.
Code Javascript:
$(document).ready(function() {
$("#btn-login").click(function() {
const loginAuth = $("#login-auth").val();
const passAuth = $("#pass-auth").val();
$.ajax({
type: "POST", //Request type
url: "http://localhost/game/login.php",
data: {
loginAuth: loginAuth,
passAuth: passAuth
},
cache: false,
success: function(data) {
console.log(data);
}
});
});
});
Code PHP:
<?php
require ('connect.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['loginAuth'])) {
// removes backslashes
$username = stripslashes($_REQUEST['loginAuth']);
// escapes special characters in a string
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_REQUEST['passAuth']);
$password = mysqli_real_escape_string($con, $password);
// Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE login='$username'
and password='" . md5($password) . "'";
$result = mysqli_query($con, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if ($rows == 1) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$arr = 'udało się';
header("Location: panel.php");
}
else {
$arr = false;
header("Location: panelLogin.php");
}
}
else {
}
echo json_encode($arr);
?>
Thank you very much for every help.
you cannot redirect the user from the php script that is being called from ajax call.
because it will redirect but not on your browser instance but the ajax one.
you need to redirect it from javascript.
so you can do
echo "true";
instead of
header("Location: panel.php");
and echo "false"; // in case login failed
as an example but you can print some json text and use more informative messages
and you can check these values from ajax success function then you can do
window.location.href = "the url you want to redirect to";

Returning AJAX Success and Error

I have built a login script that uses AJAX to submit form data.
The PHP part works fine without AJAX. But the system doesnt work with AJAX Implementation.
It always Displays the below message even though the PHP file returns true[correct username & password] ... Seems like the if condition in Jquery is not working.
Incorrect Username/Password
HTML Result Div
<div id="user-result" align="center"></div>
Jquery
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data == "true") {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>
fn_login.php
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo "true";
}
else {
die();
}
}
}
?>
Can someone please point out the mistake in the code/practice.
EDIT
Just Tried disabling AJAX, the PHP file works correctly echoing true when username/pass is correct
You have spaces after ?>
So, the AJAX response is having spaces after true.
Solution:
Remove ?> from the end of PHP file.
It will not affect any PHP functionality.
And you AJAX response will be without spaces.
Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.
Tips for debugging AJAX:
1) Always use Firefox (with Firebug Add) on Or Chrome.
2) Use Console tab of Firebug, to check which AJAX requests are going.
3) Here, you can see input parameters, headers and most important response.
4) So, in short you can debug a whole AJAX request life cycle.
You can echo json_encode(array('success'=>true)) from php code and modify your if condition in jquery with if(data.success){} Your modified code becomes
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo json_encode(array('success'=>true));
}
else {
die();
}
}
}
AND JQuery becomes
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data.success) {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>

Categories