Can't login to hosted website because of Javascript - javascript

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

Related

javascript - Save data in local storage into myphpadmin's database

hye.. im trying to create a quiz game but now im stuck and already spend hours to try transferring local storage data into database but still the data can't be recorded in database.
this is my js code:
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
$('input[type="text"]').each(function(){
var id = $(this).attr('id');
var score = $(this).val();
localStorage.setItem(id, score);
});
location.href = "wheel2.html";
});
then, to show collected marks:
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect+=10;
}
}
score.append('You got ' + numCorrect + ' marks!! ');
return score;
}
im also already try to use this code:
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "marks" + score;
xhr.open("POST", "marks.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
this is my php code:
<?php
//provide your hostname, username and dbname
$host = "localhost";
$user = "root";
$password = "";
$dbname = "test1";
$conn = new mysqli($host, $user, $password, $dbname);
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$sql = "INSERT INTO participant (marks)
VALUES ('".$_POST['marks']."')";
{
echo"<script>alert('successfully registered')</script>".' back ';
header('location:wheel.html?message=success');
}
?>

New variable ajaxObj does not work

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

how to check username and password through url by using javascript

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

Like button increment counter not working. PHP, AJAX, MySQL, javascript

I am implementing a facebook like "Like" button counter so everytime a user clicks on the button, a DIV tag besides it retrieves it from the db and updates it (see logic of the code below). However it isn't working. Please see all codes below:-
javascript:
function likeAJAX(strName)
{
If(strName == "")
{
document.getElementById('likeCount').innerHTML="";
return;
}
else
if(window.XMLHttpRequest)
{
xmlHTTP = new XMLHttpRequest();
}
else
{
xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHTTP.onreadystatechange = function()
{
if(xmlHTTP.readystate == 4 && xmlHTTP.status == 200)
{
document.getElementById('likeCount').innerHTML = xmlHTTP.responseText;
}
}
xmlHTTP.open("GET","getLikes.php?n=" + strName,true);
xmlHTTP.send();
}
HTML/PHP front-end:
<img src="./images/like.jpg" style="cursor:hand;" onclick="likeAJAX(<?php echo $_GET['val']; ?>)"><?php echo $likeVal; ?> people like this</span>
PHP/MySQL:
<?php
$q = $_GET['n'];
$temp;
$con = mysql_connect('localhost','xxxx','xxxx');
mysql_select_db("xxxx");
$SQLQuery = "SELECT * FROM likes where name= '" . $q . "'";
$res = mysql_query($SQLQuery);
while($data = mysql_fetch_array($res))
{
$temp = $data['likes'];
}
mysql_free_result($res);
mysql_close($con);
if($temp == "")
{
$temp = "0";
}
$intCount = int($temp);
$intCount++;
$con = mysql_connect('localhost','xxxx','xxxx');
mysql_select_db("xxxx");
$SQLQuery = "UPDATE likes set likes = '" . $intCount . "' WHERE busname = '". $q . "';";
$res = mysql_query($SQLQuery);
mysql_free_result($res);
mysql_close($con);
echo $intCount;
?>
Apologies for any formatting issues.
Where am i going wrong? The way i see it, seems like upon clicking the Like image, the javascript function doesn't even seems to be called?
Regards,
Ochen
Try this correction to your js:
function likeAJAX(strName) {
if (strName == "") {
document.getElementById('likeCount').innerHTML="";
return;
} else {
if(window.XMLHttpRequest) {
xmlHTTP = new XMLHttpRequest();
} else {
xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHTTP.onreadystatechange = function() {
if (xmlHTTP.readystate == 4 && xmlHTTP.status == 200) {
document.getElementById('likeCount').innerHTML = xmlHTTP.responseText;
}
}
xmlHTTP.open("GET","getLikes.php?n=" + strName,true);
xmlHTTP.send();
}
}

AJAX Sends back entire page instead of result

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!

Categories