i am developing hybrid application by using intel xdk tool and jquery mobile framework for UI. i am trying to implement login function which means i just type username and password and click submit button. while cliking button i am calling javascript function for checking username and password whether it is correct or not. this is my javascript function for login
var user, pwd ;
var xmlHttp = null;
var val;
$("#Login").click(function(event){
event.preventDefault();
user = $("#username").value() ;
pwd = $("#password").value() ;
validateForm();
});
function validateForm() {
var url ="http://schoolsmartconnect.com/android/parent_login.php?key=agile89rise98&username="+user+"&password="+pwd;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "POST", Url, true );
xmlHttp.send( null );
if (val == "1") {
window.location = "page2.html";
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText == "1" )
{
var val = xmlHttp.responseText;
}
}
}
this is my severside PHP script
<?php
require_once 'db.php';
$user = base64_decode($_REQUEST['username']);
$pass = base64_decode($_REQUEST['password']);
$key = $_REQUEST['key'];
$password = md5($pass);
if($key=="agile89rise98"){
//echo $password;
$query = mysql_query("SELECT * FROM puserprofile WHERE username ='$user' AND password = '$password' and Status=1");
$rownum = mysql_num_rows($query);
if(0 < $rownum)
{
echo 1;
}
else
{
$query2 = mysql_query("SELECT * FROM puserprofile WHERE username ='$user' and Status=1");
$rownum2 = mysql_num_rows($query2);
if(0 == $rownum2) {
$query3 = mysql_query("SELECT * FROM puserprofile WHERE password = '$password' and Status=1");
$rownum3 = mysql_num_rows($query3);
if (0 == $rownum3) {
echo 0;
}
else if(!preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5,31}$/', $user){
echo "username invalid";
}
else {
echo "Invalid username";
}
} else {
$query3 = mysql_query("SELECT * FROM puserprofile WHERE password = '$password' and Status=1");
$rownum3 = mysql_num_rows($query3);
if (0 == $rownum3) {
echo "Invalid password";
} else {
echo 0;
}
}
}
}
?>
My Requirement:-
i am sure my php script is correct, but In my javascript function i have to send my username and password request to server and get response also, if my response is equal to "1" then it redirect appropriate page otherwise it should display error messages
For your need, why don't you just retrieve username and password from the input fields instead of getting them from the url.
It will be easy enough to get the values from the input fields and validate them.
Do something like this
<input type="text" id="user"/>
<input type="password" id="pwd"/>
<input type="submit" id="submit"/>
And in the script, do this
var user, pwd ;
$("#submit").click(function(event){
event.preventDefault();
user = $("#user").value() ;
pwd = $("#pwd").value() ;
validateForm();
});
UPDATE
Now the script will look like this
var user, pwd ;
var xmlHttp = null;
var val;
$("#Login").click(function(event){
event.preventDefault();
user = $("#username").value() ;
pwd = $("#password").value() ;
validateForm();
});
function validateForm() {
var url ="http://schoolsmartconnect.com/android/parent_login.php?key=agile89rise98&username="+user+"&password="+pwd;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText === "1" )
{
var val = xmlHttp.responseText;
if (val == "1") {
window.location = "page2.html";
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
}
}
Related
I've tried to host my website to a provider but it looks like it doesn't want to login there.. On the localhost it works just fine, but uploaded at a provider it looks like it doesn't want to perform the login operation...I can successfully sign-up, change password, so basically I have database connection, but I just can't login to the website... Is it something I should modify? Here's my code:
If I'm entering for example https://example.com/login.php?enterID=123&password=123 in the website link,I can get a good response, but it looks like it doesn't allow me to login to the website..
Login.php:
<?php
include "mysql-connect.php";
//get Info from login.html
$ID = $_GET['enterID'];
$PW = $_GET['password'];
$stmt = $connect->prepare("SELECT PW, userType, nickName FROM users WHERE ID = ?");
$stmt->bind_param("s",$ID);
$valid = $stmt->execute();
if (!$valid){
die("Could not successfully run query.". $connect->connect_error);
}
$result = $stmt->get_result();
if ($result->num_rows==0){
//display message of no such student/teacher/admin
echo "Failed to find an account with the input ID.";
} else {
$row = $result->fetch_assoc();
if ($PW == $row['PW']) {
$type = $row['userType'];
$nick = $row['nickName'];
//save data, record cookie for 6hours
setcookie("type", $type, time() + 21600, '/');
setcookie("userID", $ID, time() + 21600, '/');
setcookie("nickName", $nick, time() + 21600, '/');
//login success - Request.responseText to checklogin.js
echo $type;
} else {
//display message of password error
echo "The input password does not match the account password.";
}
}
$connect->close();
?>
checklogin.js:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var Request = new XMLHttpRequest();
var info = "?enterID=" + enterID + "&password=" + password;
Request.open("GET", "php/login.php" + info, true);
Request.send();
Request.onload = function() {
var respond = Request.responseText;
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student"){
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher"){
window.location.href = "page/teacher-dashboard.php";
} else{
document.getElementById("errorMessage").innerText = respond;
}
}
} else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
var Request = new XMLHttpRequest();
Request.open("GET", "php/redirect.php", true);
Request.send();
Request.onload = function() {
var respond = Request.responseText;
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student"){
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher"){
window.location.href = "page/teacher-dashboard.php";
}
}
}
}
Redirect.php:
<?php
if (isset($_COOKIE["type"])){
setcookie("type", $_COOKIE["type"], time() + 21600, "/");
setcookie("userID", $_COOKIE["userID"], time() + 21600, "/");
setcookie("nickName", $_COOKIE["nickName"], time() + 21600, "/");
echo $_COOKIE["type"];
} else {
echo "not logged.";
}
?>
TImeoutAndRedirect function:
function TimeoutAndRedirect(Type) {
var Request = new XMLHttpRequest();
Request.open("GET", "../php/redirect.php", true);
Request.send();
Request.onload = function() {
var respond = Request.responseText;
if (respond == "not logged.") {
alert("Your login period has expired! Please login again!");
window.location.href = "../login.html";
} else if (respond != Type) {
alert("You cannot access this page using your account!");
if (respond == "admin") {
window.location.href = "../page/admin-system-management.php";
} else if (respond == "student"){
window.location.href = "../page/student-dashboard.php";
} else if (respond == "teacher"){
window.location.href = "../page/teacher-dashboard.php";
}
}
}
}
On line 24 where I test if the test2[1] == "invalid" never works it always goes to the else and takes me to the next page. I think test2[1] just isn't a string but I don't know what else it would be please help
function login() {
var email = document.getElementById("email").value;
var passW = document.getElementById("password").value;
if (email == "" || passW == "") {
alert("Please enter a valid email or password.");
} else {
var myXMLRequest = new XMLHttpRequest();
myXMLRequest.onload = openWorkout;
var url = "assignment10.php?em=" + email + "&pass=" + passW;
myXMLRequest.open("POST", url, true);
myXMLRequest.send();
}
}
function openWorkout() {
var invalid = "invalid";
var step = this.responseText;
var test = step.split(",");
var test2 = test[0].split(":");
console.log(step);
console.log(test);
console.log(test2[1]);
if (test2[1] == "invalid") {
alert("The email or password you entered is invalid. Please try again.");
} else {
window.location = "#workoutPage";
}
}
<?php
//TASK 1: MAKE A CONNECTION TO THE DATABASE, DISPLAY ERROR FOR FAILED CONNECTIONS
//(FOR GODADDY) NOTE: $mysqli = new mysqli("127.0.0.1", "username", "password", "database", 3306);
$mysqli = new mysqli("localhost", "User", "1234", "ass10");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//CHECK IF EMAIL AND ENTERED PASSWORD VALID (LOGIN PAGE [first part of open workout checks login password])
$entEmail = $_GET['em'];
$entPassword = $_GET['pass'];
$sql = "SELECT * FROM membership_table WHERE Email = $entEmail, Password = $entPassword";
$result = $mysqli->query($sql);
if($result->num_rows == 0) {
$data = "invalid";
} else {
$data = "valid";
}
//Pass to JSON
$json = array(
"data" => $data,
"Email" => $entEmail,
"Password" => $entPassword
);
header("Contenttype:Application/json");
print(json_encode($json));
?>
here are the console.log outputs on lines 21 - 23
assignment10.js:21 {"data":"invalid","Email":"q","Password":"1"}
assignment10.js:22 (3) ["{"data":"invalid"", ""Email":"q"", ""Password":"1"}"]
assignment10.js:23 "invalid"
You're returning JSON from your PHP, so process it as that using JSON.parse, rather than trying to split the string apart:
var response = JSON.parse(this.responseText);
var test = response.data;
if (test == 'invalid') {
...
Note the issue with your current code is that test2[1] is literally "invalid", including the double quotes, so for your test to work you'd need to use
if (test2[1] == '"invalid"') {
Here's a snippet to demonstrate the code using the output of console.log(step) from your question:
const responseText = '{"data":"invalid","Email":"q","Password":"1"}';
var response = JSON.parse(responseText);
var test = response.data;
if (test == 'invalid') {
console.log('Invalid!');
} else {
console.log('Valid!');
}
As I was coding I encountered an absolute annoying error when callbacking the responseText from PHP.
Now the issue is that, when I run the fpass.php file, and fill out the data, everything works except when callbacking the responseText, for example if it prints out MAIN_FPASS_USER_NO_MATCH from the PHP file it should change the _('status').innerHTML to a different text of my choice, and not what the PHP printed. Some ideas for what I missed in my code?
JS Script:
function fpass(){
var e = _("email").value;
if(e == ""){
_("status").innerHTML = "Type in your email address</br></br>";
} else {
_("fpassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "/fpass.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'MAIN_FPASS_SUCCESS'){
_("fpassform").innerHTML = '<h3>Step 2. Check your email inbox in a few minutes</h3><p>You can close this window or tab if you like.</p>';
} else if(ajax.responseText == "MAIN_FPASS_USER_NO_MATCH"){
_("fpassbtn").style.display = "none";
_("status").innerHTML = "Sorry that email address is not in our system";
} else if(ajax.responseText == "MAIN_FPASS_EMAIL_FAILURE"){
_("fpassform").innerHTML = "Mail function failed to execute";
} else if (ajax.responseText == "MAIN_FPASS_EXISTS") {
_("fpassform").innerHTML = "already fpass";
} else {
_("status").innerHTML = ajax.responseText;
}
}
}
}
ajax.send("e="+e);
}
JS Functions:
// getElementById Function
function _(x){
return document.getElementById(x);
}
// emptyElement Function
function emptyElement(x){
_(x).innerHTML = "";
}
Ajax Functions:
function ajaxObj(meth, url){
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//x.send(data);
return x;
}
// END Ajax Object
// Start Ajax Return
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
HTML Code:
<span id="status"></span>
<form id="fpassform" onsubmit="return false;">
<input id="email" type="text" placeholder="Email" onfocus="emptyElement('status')" maxlength="88">
<button id="fpassbtn" onclick="fpass()">Reset</button></br>
</form>
PHP Code:
// AJAX CALLS THIS CODE TO EXECUTE
if(isset($_POST['e'])){
include_once("vendor/db.php");
$e = $mysqli->real_escape_string($_POST['e']);
$usql = "SELECT * FROM users WHERE useremail='$e' AND activated='1' LIMIT 1";
$uresult = $mysqli->query($usql);
$unumrows = $uresult->num_rows;
if($unumrows == 1){
$fpsql = "SELECT * FROM forgotpass WHERE useremail='$e' LIMIT 1";
$fpresult = $mysqli->query($fpsql);
$fpnumrows = $fpresult->num_rows;
if($fpnumrows == 0) {
if($fetch = $uresult->fetch_array(MYSQLI_FETCH_ASSOC)){
$u = $fetch["username"];
$e = $fetch['useremail'];
$pn = $fetch['userphone'];
$fpkey = substr(md5(uniqid($u)), 0, 14);
$sql = "INSERT INTO `forgotpass` (username,useremail,userphone,fpkey)
VALUES ('$u','$e','$pn','$fpkey') ";
if($mysqli->query($sql)) {
$to = "$e";
$from = "auto_responder#yoursite.com";
$headers ="From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \n";
$subject ="yoursite Temporary Password";
$msg = 'MSG here';
if(mail($to,$subject,$msg,$headers)) {
echo 'MAIN_FPASS_SUCCESS';
exit();
} else {
echo 'MAIN_FPASS_MAIL_FAILURE';
exit();
}
}
}
} else {
echo 'MAIN_FPASS_EXISTS';
exit();
}
} else {
echo 'MAIN_FPASS_USER_NO_MATCH';
exit();
}
exit();
}
For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.
I am having a little trouble figuring out why my ajax response is sending me the entire page.
I am not using conventional AJAX code simply because this is how the guy was doing it in a tutorial I was following. I am using firebug to track all my javascript variables and when I break the code at the responseText var it gives me the entire page. Here is the code for the javascript on the page I am working with :
function changepass() {
var u = _("username").value;
var cp = _("currentPass").value;
var np = _("newPass").value;
var cnp = _("confirmNewPass").value;
if(np != cnp) {
_("status").innerHTML = "The passwords given do not match!";
} else if (cp === "" || np === "" || cnp === "") {
_("status").innerHTML = "Please fill out all of the fields.";
} else {
_("changepassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "change_password.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var response = ajax.responseText;
if(response == "success"){
_("status").innerHTML = "Your password change was successful! Click the button below to proceed.<br><br>Back To Home Page";
} else if (response == "no_exist"){
_("status").innerHTML = "Your current password was entered incorrectly.";
_("changepassbtn").style.display = "initial";
} else if(response == "pass_failed"){
_("status").innerHTML = "Change password function failed to execute!";
_("changepassbtn").style.display = "initial";
} else {
_("status").innerHTML = "An unknown error occurred";
_("changepassbtn").style.display = "initial";
}
}
}
ajax.send("u="+u+"&cp="+cp+"&np="+np+"&cnp"+cnp);
}
}
Here is the AJAX code that I use to handle the requests.
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Any help would be greatly appreciated.
Thanks!
Here is the server side PHP:
if(isset($_POST["u"]) && isset($_POST['oe']) && isset($_POST['ne']) && isset($_POST['p'])) {
$oe = mysqli_real_escape_string($db_conx, $_POST['oe']);
$ne = mysqli_real_escape_string($db_conx, $_POST['ne']);
$p = md5($_POST['p']);
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
var_dump($oe, $ne, $p, $u);
$sql = "SELECT username, password, email FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_username = $row[0];
$db_password = $row[1];
$db_email = $row[2];
var_dump($db_username, $db_password, $db_email);
if($db_email != $oe) {
echo "bad_email";
exit();
} else if($db_password != $p) {
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET email='$ne' WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$sql = "SELECT email FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newemail = $row[0];
if($db_newemail == $ne) {
echo "success";
exit();
} else {
echo "email_failed";
exit();
}
}
}
My mistake was a simple syntax error. Gosh PHP is picky! The error occurs in the ajax.send command. I am miss an '=' on the last parameter.
Thanks for your help guys!