Cannot get the value from JSON - php

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'...

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

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.

Login PHP Session not working

I have a login form that checks the password and username entered and if correct it will give a message and makes login session true. But the session doesn't work. When it redirects you to dashboard you won't be able to visit it the value of session login is unknown. So when you enter userpass correct the session is not created for that moment but when you redirect it to another page your session is gone.
<?PHP
session_start();
// Starting session
include 'config.php';
$pass = $_POST['pass'];
$user = $_POST['user'];
if (isset($_POST['user']) and isset($_POST['pass'])){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $link->query("SELECT user FROM users2 WHERE user = '$user'");
if($result->num_rows == 0) {
echo '<script type="text/javascript">
$(document).ready(function(){
demo.initChartist();
$.notify({
icon: "pe-7s-bell",
message: "Username of password was wrong. Please try again."
},{
type: "info",
timer: 4000
});
});
</script>';
} elseif ($result->num_rows == 1){
$userpass = $link->query("SELECT pass FROM users2 WHERE user = '$user'");
$row = $userpass->fetch_assoc();
$userpasss = $row["pass"];
if ($pass == $userpasss){
echo '<script type="text/javascript">
$(document).ready(function(){
demo.initChartist();
$.notify({
icon: "pe-7s-bell",
message: "You are logged in successfully! Redirecting ..."
},{
type: "info",
timer: 4000
});
});
</script>';
$_SESSION['login'] = "true";
$_SESSION['username'] = "$user";
echo "<meta http-equiv='refresh' content=3;URL='dashboard.php' /> ";
echo $_SESSION["login"];
echo $_SESSION["username"];
// Storing session data
} else {
echo '<script type="text/javascript">
$(document).ready(function(){
demo.initChartist();
$.notify({
icon: "pe-7s-bell",
message: "Username of password was wrong. Please try again."
},{
type: "info",
timer: 4000
});
});
</script>';
}
}
}
echo $_SESSION["login"];
?>
Where is the problem in the code?
Thank you
Warm regards
Put session_start(); at the Top of this page as you are accessing in global scope so you will get the session value.
And i will suggest you to create different file for authentication purpose.
You need to write all the page of the top session_start()
After successful login then redirect to dashboard.php need to add the first line
<?php session_start(); echo $_SESSION['login]; ?>

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

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