PHP file not running in AJAX? - php

My AJAX function is not running my PHP script. I have a similar function for my signup and it is working without any issues. The AJAX function runs to the end of the done call but the first line in the PHP file that creates a cookie does not run.
I have outputted the data(result) to console and that all looks good. No errors come up and I have enabled PHP errors on my server which I have full control over. The server is fine as this exact approach was used for the sign-up portion of the website and it works.
JQuery
$('#login-form').on("submit", function(e){
var dataString = $(this).serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString
}).done(function (result, status, xhr) {
// Display message back to the user here.
window.location.replace('./app/');
console.log("Login Completed!");
}).fail(function (result) {
// TASK: Add a visual element on the page for errors.
if (result.status == 522){
alert("Email not verified!");
} else if (result.status == 523){
alert("Password was incorrect!");
} else if (result.status == 524) {
alert("User account not found!");
}
});
return false;
});
PHP
<?php
setcookie("TestCookie", "login.php", none, "/");
if (array_key_exists('emailAddress', $_POST) && array_key_exists('password', $_POST)){
$emailAddress = $_POST["emailAddress"];
$password = $_POST["password"];
// Connect to the database with this standard connect PHP script.
include('connectDB.php');
// Check the link was established.
if (!mysqli_connect_error()) {
$sqlget = "SELECT id, emailAddress, userPassword, userRole, emailVerified FROM users WHERE emailAddress=\"$emailAddress\"";
$sqldata = mysqli_query($dbconn, $sqlget);
if (mysqli_num_rows($sqldata) == 1){
// One user was found.
$userInfo = mysqli_fetch_array($sqldata);
setcookie("Account", "found", none, "/");
if ((password_verify($password, $userInfo["userPassword"])) {
setcookie("Password", "OK", none, "/");
if ($userInfo["emailVerified"] == true) {
setcookie("loginId", $userInfo["id"], none, "/");
} else {
// Email was not verified.
header('HTTP/1.1 522 Email Not Verified');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// Password verification failed.
header('HTTP/1.1 523 Password verification Failed');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// No user found in the system
header('HTTP/1.1 524 User not Found');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// Place code to tell the user there was an internal DB error.
// Possibly a standard error message. Lets not scare the user.
header('HTTP/1.1 500 Internal Server Error');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
}
?>

I found the problem. I had one too many brackets on line 18. I changed the line to the following and the PHP script ran.
if (password_verify($password, $userInfo["userPassword"])) {
if ($userInfo["emailVerified"] == true) {
setcookie("loginId", $userInfo["id"], 0, "/");
} else {
// Email was not verified.
header('HTTP/1.1 522 Email Not Verified');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// Password verification failed.
header('HTTP/1.1 523 Password verification Failed');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}

Related

JQUERY AJAX GET and POST accessing different files?

I am doing email verification on my website. When user submits the form, it starts ajax post request, which posts the email to PHP which compares it with a datebase.
Than still in the form verification process, I have ajax GET request, which should return from the same PHP file whether the email has already been used.
But. Everything works fine when I proceed to the PHP, but GET request is always blank. URL of POST request is EmailDuplication.php but URL of GET is EmailDuplication?_=somerandomnumbers. Might that be the problem?
I am not experienced in this, will be glad for any help.
Here are the codes
JavaScript
function EmailSendForDupe()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'post',
async: false,
cache: false,
timeout: 30000,
data: {email: email.toString},
success: function (){
window.alert("email sent");
}
});
}
function EmailDuplication()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
async: false,
cache: false,
timeout: 30000,
success: function (callback){
console.log(callback.length);
console.log(callback);
if (callback.length !== 0){
window.alert("Email is already in use");
return false;
}
else {
window.alert("Email valid");
return true;
}
}
});
}
PHP
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}
else {
echo "User Email is already in use.";
}
}
?>
First, I would advise cleaning up your PHP and making sure it is not vulnerable to SQL Injection.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
$returnData = new array();
$conn = mysqli_connect($servername, $username,$password,$dbname);
if (mysqli_connect_errno()) {
$returnData['SQL Error'] = "Connect failed: %s\n", mysqli_connect_error();
header('Content-Type: application/json');
echo json_encode($returnData);
exit();
}
if(isset($_POST['email'])){
// POST
$email = mysqli_real_escape_string($conn, $_POST['email']);
$resultData["AHOJ"] = true;
$Emailquery = "SELECT * FROM Members WHERE email='$email' LIMIT 1;";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
$resultData['inUse'] = false;
$resultData['email'] = $_POST['email'];
} else {
$resultData['inUse'] = true;
}
} else {
// GET
$resultData["AHOJ"] = false;
$resultData['inUse'] = true;
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($returnData);
die();
?>
This will return JSON details back to your jQuery script and can be more helpful than plain text.
I also use mysqli_real_escape_string() to help escape any potential injection attempts. I would advise switching to Prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php
In your JavaScript, you will want to make a few changes too.
function EmailSendForDupe(email){
$.ajax({
url: '/files/EmailDuplication.php',
type: 'post',
cache: false,
timeout: 30000,
data: {
email: email.toString()
},
dataType: "json",
success: function (json){
console.log(json);
if(json.inUse == false){
alert("Email Sent to " + json.email);
} else {
alert("There may have been an error: " + json.error);
}
}
});
}
function EmailDuplication(email){
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
data: {
email: email.toString()
},
dataType: "json",
cache: false,
timeout: 30000,
success: function (json){
console.log(json);
if (json.inUse){
window.alert("Email is already in use");
} else {
window.alert("Email valid");
}
}
});
}
Hope this helps.
Generally you want to use async: true.
Also, you do not want to allow the form submit to actually Happen, as that blows away your whole page (reloads the entire thing, if not navigates to somewhere else entirely). So in fact the blank get you could be seeing could be the form submit blowing away your page.
If you are sending ajax requests, the trigger for those simply needs to be a button with a click handler, not an actual submit (unless in that submit input you do something like "onclick='doMyAjax();return false;'" so that the submit action does not actually occur).
If you are actually uploading a file, which for the purpose you appear to be showing here dear goodness please don't let the client drive that functionality via files on their system, the upload post needs a target to post To, so it does not hit your page. For that, the classic embedding of an iframe is still the way to go. Ugh.
posting to an iframe
I have no idea why Two requests need to be sent to do the job. It should probably be just one POST (assuming the ultimate outcome here is you want to send an email if it is a valid email), and the server checks the email and then does the send if it is valid.
And do not use GET versus POST to distinguish what the server should do (such as verifying an email versus sending one) - the Request itself or the Url, for example include "action=verifyEmail" in your form data being passed up, to tell the server what to do rather than it assuming just because it's a POST.
Hopefully some of this is helpful.
you are missing to handle GET Request Data.if some try to using get URL then your code don't have any condition to handle it. check modified code.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}else {
echo "User Email is already in use.";
}
}else{
echo " Get Method Data";
}
?>
Please try it and give your feedback.

Ajax failing with status 0

My ajax request is always failing with status 0. The PHP file being called is executing all the code. I am unable to locate the reason why the request is failing.Here is the ajax code:
$(document).ready(function() {
// Get the form.
var form = $('#reg-form');
// Get the messages div.
var formMessages = $('#login_form');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
//e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
alert("Data submitted");
var submitresponse = $.ajax({
type: 'POST',
url: "mailer.php",
data: formData,
dataType: "json",
});
submitresponse.done(function(response) {
alert("Hi");
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
alert(response);
// Set the message text.
$(formMessages).text(response);
// Clear the form.
//$('#name').val('');
//$('#email').val('');
//$('#Address').val('');
});
submitresponse.fail(function(xhr,status,response) {
alert("Hii");
console.log(arguments);
alert(status);
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
//if (data.responseText !== '') {
alert(xhr.responsetext);
// $(formMessages).text(data.responseText);
//} else {
//$(formMessages).text('Oops! An error occured and your message could not be sent.');
//}
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
// This is the default error handler for ajax request.
// Extract all the information required to understand.
var requestResponse = {
url: ajaxSettings.url,
method: ajaxSettings.type,
data: ajaxSettings.data,
httpStatus: jqXHR.status,
error: thrownError || jqXHR.statusText,
data: ajaxSettings.data
};
console.error(requestResponse)
// Notify the user so he might not wonder.
alert('Something went wrong, Please try again');
});
});
});
});
The PHP Code is as follows:
<?php
$servername = "*";
$username = "*";
$password = "*";
$dbname = "*";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
//die("Connection failed: " . $conn->connect_error);
die("Something went wrong. Please try again or contact front desk. <br/>");
}
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$address = trim($_POST["Address"]);
$class = $_POST["class"];
$school = $_POST["school"];
$city = $_POST["City"];
$fname = $_POST["f_name"];
$mobileno = $_POST["mobileno"];
// Check that data was sent to the mailer.
if ( empty($name) OR empty($address) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$sql = "INSERT INTO registrations(Name, Father_Name,Email,Class,School,Address,City,Mobile_No,Reg_time) values ('$name','$fname','$email','$class','$school','$address','$city',$mobileno,now())";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
//echo "Your Information Was Successfully Posted";
mysqli_close($conn);
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = $email;
// Set the email subject.
$subject = "ISMART Registration";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$address\n";
$email_content .= "Class: $class\n";
// Build the email headers.
$email_headers = "From: ismart#asd.co.in";
// Send the email.
if (mail($recipient, $subject, $email_content,$email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Console log shows:
Object {url: "mailer.php", method: "POST", data: "name=Nitish+Garg&f_name=sdfs&class=11&school=DAV+P…+1-A%2C+PWSSB+House%2C+Barakuan+Road&City=Patiala", httpStatus: 0, error: "error"}
Please help!
httpStatus with a 0 means that the Ajax call isn't getting a complete response from the server. There's a disconnect somewhere and you're either not getting anything from the server or just not the full response. I'd check on timeouts first.

Ajax & PHP login form, issues with validation. Multiple troubles

I'm trying to turn my login form into a drop down using ajax and jquery. So far I've got everything working except the ajax and error validation.
Currently the main issue I have is when a field is not entered, password for example. The login box displays "this field is required" which is great, if I then click on submit again the input field disappears and the message remains. I can't continue with login unless I refresh the page.
The other main issue is getting the error message from the php. If I input the wrong password, the message doesn't get displayed. The form submits, goes away and that's it. When I select login again I can see the error message that should have been displayed previously.
On a plus side : A correct login combination works perfectly.
Any help is appreciated.
Both PHP and Function are pasted below.
function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}
var params = "username="+username+"&password="+password;
var url = "loginProcessAjax.php";
$("#status").show();
$("#status").fadeIn(400).html('<img src="image/loading.gif" />');
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("status").innerHTML= 'checking...' ;
},
complete: function() {
},
success: function(html) {
$("#status").hide();
document.getElementById("status").innerHTML= html;
if(html=="success"){
window.location = "index.php"
}
}
});
}
<?php
//check fields are filled in
if(empty($_POST) === false){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//validate fields
if(empty($username) === true || empty($password) === true){
$errors[] = 'Your username and password are needed.';
}else if($users->userExists($username) === false){
$errors[] = 'That username does not exist';
}else if($users->emailActivated($username) === false){
$errors[] = 'You need to activate the account, please check your email.';
}else{
//start login
$login = $users->login($username, $password);
if($login === false){
$errors[] = 'That username or password is invalid';
if(empty($errors) === false){
echo '<p>' .implode('</p<p>', $errors).'</p>';
}
}else{
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
//send user to their home page
echo "success";
header('Location: userHome.php');
exit();
}
}
}
EDIT: Just checked again, now if I leave any of the fields blank or if they are incorrect no error is displayed. The second scenario above is constant unless correct details are provided.

Cannot get the value from JSON

this is the code in php
<?php session_start();
//Connect to database from here
$link = mysql_connect('****', '****', '****');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//select the database | Change the name of database from here
mysql_select_db('****');
//get the posted values
$user_name=htmlspecialchars($_GET['user_name'],ENT_QUOTES);
$pass=$_GET['password'];
//now validating the username and password
$sql="SELECT user_name, password FROM tbl_user WHERE user_name='".$user_name."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// Return success message
$message = array("flag" => "1", "msg" => "Login successfully.");
echo json_encode($message);
//Regenerate session ID to prevent session fixation attacks
//session_regenerate_id();
//now set the session from here if needed
//$_SESSION['u_name']=$user_name;
//$member=mysql_fetch_assoc($result);
//$_SESSION['u_id']=$member['id'];
//$name_show=$member['first_name'].' '.$member['last_name'];
//$_SESSION['name']=$name_show;
//Write session to disc
//session_write_close();
}
else
// Return error message
$message = array("flag" => "0", "msg" => "Incorrect password.");
echo json_encode($message);
}
else //if username not exists
{ // Return error message
$message = array("flag" => "0", "msg" => "Incorrect id.");
echo json_encode($message);
}
mysql_close($link);
?>
this is the code in html
$.ajax({
type: "get",
url: "http://mydomain.com/ajax_login.php",
data: {
user_name: $("#username").val(),
password: $("#password").val()
},
success: function(jsondata){
if (jsondata.flag == "0"){
//if flag is 0, indicate login fail
}
else {
//if flag is 1, indicate login success and redirect to another page
window.location.href = 'ABC.html';
}
},
datatype: "json"
});
display shows "{\"flag\":\"0\",\"msg\":\"Incorrect id.\"}"
my question is that, now even the flag is 0, it still goes to ABC.html
what should the if clause to be modified such that if the flag is 0, it will still in the true part of the clause??
EDITED this is the more detail of the coding
Be sure to configure your ajax call with dataType: "json" in you jQuery ajax method, and be sure to send JSON header in your PHP response like.
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");
echo json_encode($yourArray);
If you don't onfigure your ajax call correctly, the result could be interpreted as a simple string.
Perhaps jsondata.flag is undefined.
You need to decode response string to use it as JS object.
Or set dataType : 'json'...

PHP and jQuery AJAX $_SESSION Bug

I spent many days to fix this problem and i can't find a solution.
After i login using my ajax form + php backend, the page where user is redirected show the "Missing session" message and if i try dumping $_SESSION it looks like empty. Then, if i go back and i do the same login it will work correctly. This happen in different browser (usually when they have cookie and cache clear) and in different hosting providers.
This is my ajax code:
$(document).ready(function(){
$('#loginbtn').click(function(){
if($('#username').val() == "" || $('#password').val() == ""){
return false;
}
else
{
$.ajax
({
type: 'POST',
url: 'ajax_login.php',
cache: false,
dataType: 'json',
data:
{
username: $('#username').val(),
password: $('#password').val()
},
success:function(data)
{
if(data.error === true){
alert("Failed to login: "+data.message)
}
else
{
setTimeout(function()
{
window.location = 'http://www.mywebsite.com/dashboard.php';
},2000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("An error occured!");
}
});
return false;
}
});
});
This is the PHP Login Backend:
<?php
include "config.php"; // start session and connect to mysql db, also contain functions sanitize(), getip()
$username = sanitize(htmlspecialchars($_POST['username'],ENT_QUOTES));
$pass = sanitize($_POST['password']);
// FUNCTION TO LOGIN
$sql = mysql_query("SELECT * FROM members WHERE username = '$username' AND password = '$pass'");
$array = mysql_fetch_array($sql);
if(mysql_num_rows($sql) === 0){
$message['error'] = true;
$message['message'] = "Wrong username or password.";
echo json_encode($message);
exit;
}
$_SESSION['username'] = ucwords(strtolower($username));
$_SESSION['points'] = $array['points'];
$_SESSION['ip'] = getip();
$_SESSION['welcome'] = true;
$message['error'] = false;
$message['message'] = "Completato.";
echo json_encode($message);
exit;
And finally this is dashboard.php check session code:
<?php
include "config.php";
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
Edit: This is what's inside config.php
<?
session_start();
date_default_timezone_set("Europe/Rome");
$hostname = ""; //hostname
$data_username = "dbxxxxxxxx"; //database username
$data_password = "xxxxx"; //database password
$data_basename = "dbxxxxxxx"; //database name
$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
mysql_select_db("".$data_basename."") or die(mysql_error());
function sanitize($text) { // funzione che pulisce le stringe per prevenire exploit;
if(get_magic_quotes_gpc() == 0) {
$text = addslashes($text);
}
$text = htmlentities($text);
$text = strip_tags($text);
$escape = mysql_real_escape_string($text);
$arraydangerous = array('SELECT *', 'LOAD_FILE', 'DELETE', 'TRUNCATE', '\' OR', '<javascript>', 'src=', '<?', '?>', 'document.cookie', 'http://', 'www.');
$text = str_replace($arraydangerous, "", $text);
return $text;
}
function getip()
{
return filtra($_SERVER['HTTP_CF_CONNECTING_IP']); // I use CloudFlare ,so i must use this way :)
}
How can i fix this? Thanks
In config.php add this lines after session_start();.
session_start();
// reset the session, if not logged-in
if (empty($_SESSION['username'])) {
$_SESSION['username'] = null;
$_SESSION['points'] = null;
$_SESSION['ip'] = null;
$_SESSION['welcome'] = null;
}
Also I guess it's better you changing dashboard.php to something like this:
<?php
include "config.php";
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
?>
I think your problem is the old sessions that you have on your server, while testing your code. For example you are trying to log in, you add the values to the session but for any reason you receiving some errors, and you see that you're not logged in. You forgot that you already add some data to the session, you refresh the dashboard.php and you see that hey, it seems that you're already logged in. Then you might think that your code is crazy, working randomly or any other irrelevant reason. (a few years ago, I had a code that was working when it was raining on the day, and didn't work when it wasn't rainy. Fortunately, I solved that problem in 2 days, before getting crazy!)
You might also clean all the sessions stored on your server, to be sure you have a clean test, while you're changing the code.
I hope these gonna helps somehow.
I'm not sure if this is the case or what (since I don't know what's inside config.php), but it seems to me that you forgot to start the session before you use it in your "PHP Login Backend" file!

Categories