JQUERY AJAX GET and POST accessing different files? - php

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.

Related

PHP file not running in AJAX?

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

Throw connection error at front end php

so I am a php beginner and i was making a login app with server and client side validation .I want to throw an error to the login page when the password is wrong after matching it with db or if email is not unique ..well something like that.
Thank you
To display authentication error after checking from DB you need to use ajax
var username = "....";
var password = "....";
$.ajax({
url: "/login",
method: "POST",
data:{username,password}
}).done(function(data) {
if(data.success){
$("#msg").html("Success");
}else{
$("#msg").html(data.err_msg);
}
});
In php files
<?php
function checkAuthentication(){
$errormsg = "";
$result = true;
try {
//your data and query to check 'username' and 'password'
if(!$password_match){
$result = false;
$errormsg = 'Invalid credential';
}
} catch (Exception $exception) {
$result = false;
$errormsg = 'Database error! ' . $exception->getMessage();
}
//return json data
return json_encode(["success"=>$result,"err_msg"=>$errormsg]);
}
?>
There are much more things to do but you can think this way to start

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.

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!

How can I work on the output of jsonp in phonegap?

I am working on a PhoneGap with Android project. I have designed a login page in which I want to show an alert box for a valid and invalid user. I am using PHP for database validation.
This is my php page:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id, name,password FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
This is my java script function:
function onDeviceReady(){
var output = $('#output');
var id = document.getElementById('userid').value;
var pass = document.getElementById('password').value;
// webcam.set_api_url( 'test.php?filename=' + escape(filename));
$.ajax({
url: 'http://192.168.1.214/sample/dologin.php?id='+id+'&password='+pass,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
console.log('entered success============');
$.each(data, function(i,item){
var logi=item.id;
if(logi!=null)
alert("valid user");
else
alert("invalid user");
});
},
error: function(){
console.log('entered success====================');
output.text('There was an error loading the data.');
}
});
}
This is not working properly for an invalid user. Whenever I enter a valid user name and password then it displays the valid user message box. When I enter an invalid user name and password then it doesn't display anything.
Thank you in advance...
Try debugging this in a browser and perhaps send the returned jsonp data to the console from within your ajax's success call console.log(data).
It's quite possible that your jsonp is returning some data as opposed to null... even if it is simply undefined or an empty string. Your conditional is most likely the culprit.

Categories