Trying to see if an email is not a duplicate - php

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().

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";
}

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";

How to: Ajax check values in php/database

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);
}

how to get json response in ajax?

url : http://localhost/test-mobile/log.php?username=&password=pass
$.ajax({
url:url,
type:'POST',
data:{message:message},
dataType:'json',
json:'members',
success:successData,
error:function(){
alert("error")
}
});
function successData(data){
var response=data.message;
alert(response);
}
json response is {"members":{"httpCode":"400","message":"Username missing"}}
PHP code is given below:
<?php
require_once("class/clsdatabase.php"); //Connect to SQL
$username = $_GET['username'];
$password = $_GET['password'];
//Check Username
if($username == '') {
$user = 'Username missing';
$success = true;
$status = array("httpCode"=>"400", "message"=>$user);
//return $status;
}
//Check Password
if($password == '') {
$pass = 'Password missing';
$success = true;
}
//Create SELECT query
$qry = "select * from user_register where emp_code='$username' AND emp_password='$password' AND active='1';";
$result = mysql_query($qry);
$te = mysql_num_rows($result);
if($te == 0 && $username != '' && $password != '') {
$both = 'Invalid username or password';
$success = true;
}
//If there are input validations, redirect back to the registration form
if($te != 0 && $username != '' && $password != '') {
$row = mysql_fetch_assoc($result);
$name = $row['emp_code'];
$success = true;
$status = array("httpCode"=>"400", "message"=>$name);
//return $status;
}
//echo $_GET['callback']. '(' . json_encode($status) . ');';
echo '{"members":'.json_encode($status).'}';
?>
alert a json response
I would split the pages up into two. One file called ajax.php and another called index.php.
Your index.php will look something like.
<html>
<head>
<script type="text/javascript">
postData={ajax:"testing",id:'123'};
$.post('ajax.php', postData , function (data) {
alert(data);
});
</script>
</head>
<body>
</body>
</html>
And your ajax.php file will look something like
<?php
// its important that this file only outputs json or javascript
// content and nothing else.
if(isset($_REQUEST['ajax'])){
$ajaxRequest = $_REQUEST['ajax'];
if($ajaxRequest == 'testing'){
// do some php stuff here -- if you look at the above example we sent an id variable
$sql = "SELECT FROM table WHERE id = {$_REQUEST['id']}";
$results = query($sql);
echo json_encode($results);
exit; // exit the script here so that only the ajax stuff is output
}
}
The jQuery .ajax function automatically decodes the JSON object if the dataType:'json' parameter is set (which it is in his query). So the 'data' variable passed to the success() function will already be a javascript object.
To access the 'message' value, you would use "data.members.message" since the 'members' object contains the 'message' value.

Categories