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";
}
Related
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().
I have 2 php file, one is "Db_function.php" and "index.php", "index.php" will make a function call in "Db_function.php".
I want to make a call to "index.php" by ajax, here's my code
Html file
<Html>
<body>
<script type="text/javascript" src="js/index.js"></script>
<input type="button" value="Get" onclick="get()">
</body>
</html>
Js file
function get() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
});
}
index.php
/*with connect value*/
if ($tag == 'get_backup'){
// store user
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->get_backup($email, $password);
Db_funtion.php
public function get_backup($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
$response = array();
$result2 = mysql_query("SELECT * FROM contact_store WHERE (email ='$email' AND backup_name='$email')") or die(mysql_error());
if (mysql_num_rows($result2) > 0) {
// looping through all results
// contact_stores node
$response["contact_stores"] = array();
while ($row = mysql_fetch_array($result2)) {
// temp user array
$contact_store = array();
$contact_store["backup_name"] = $row["backup_name"];
$contact_store["email"] = $row["email"];
$contact_store["data"] = $row["data"];
// push single contact_store into final response array
array_push($response["contact_stores"], $contact_store);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no contact_stores found
$response["success"] = 0;
$response["message"] = "No contact_stores found";
// echo no users JSON
echo json_encode($response);
}
}
} else {
// user not found
return false;
}
}
Json return like this
{"contact_stores":[{"backup_name":"nhi#gmail.com","email":"nhi#gmail.com","data":"[]"}],"success":1}
But my problem is when i press get button in html file, nothing happen.
Any help for me ?
It seems like you are not defining the get() function that you provide in the input element.
Try this HTML:
<input id="get" type="button" value="Get">
with this javascript:
$('#get').click(function() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
})
});
I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
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);
}
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.