I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.
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'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.
I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.
i created a sencha touch application,in my controller i used the ajax code as
if (condition is true){
Ext.Ajax.request({
url: 'http://localhost/../abc.php?action=check',
params: valuesUser,
method: 'POST',
success: function(response){
var text = response.responseText;
console.log(response.responseText);
if(response.responseText == 'exists')
{
//Ext.Msg.alert('Success', text);
Ext.getCmp('loginform').destroy();
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
}
else{
Ext.Msg.alert('Success',text);
}
}
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
}
else{
Ext.Msg.alert('Error', 'All the fields are necessary');
}
my abc.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('RegisterForm',$con);
if($_REQUEST["action"]== "check"){
$query = "SELECT name FROM userdetails WHERE name ='" . $_POST['userName'] . "' ";
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
if($count == 1)
{
echo('values are in the db');
}
else
{
echo("values aren't in the db");
}
}
?
if contion is true in the controller code it goes to abc.php and checks name exists in the db are or n't.if name exist then it should open another view ,otherwise it should display alert msg as values aren't in the db.but by using the above code ,im navigating to another view in both cases (values are in db,values aren't in the db).can anyone help me to do this. thanks in advance...
You need to put condition in your sencha code based on the returned value from PHP. Something like:
if(response.responseText == 'exists')
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
else
Ext.Msg.alert('Success', text);
Moreover do
echo 'exists';
instead of
echo('values are in the db');
i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.