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!
Related
I need an AJAX Login Script for my school project.
But it actually won't work because when I try to login, I get kicked to the startpage (login-form) without any message.
That's my backend-script (login2.php):
if(empty($_POST['loginEmail']) || empty($_POST['loginPassword'])) {
$error[] = "Bitte füllen Sie alle Felder aus!";
}
if (!empty($_POST['loginEmail']) && !filter_var($_POST['loginEmail'], FILTER_VALIDATE_EMAIL)) {
$error[] = "Bitte geben Sie eine gültige E-Mail-Adresse an!";
}
if(count($error)>0) {
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $_POST['loginEmail']));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0) {
if(!password_verify($_POST['loginPassword'],$row[0]['uPassword'])) {
$error[] = "Falsches Passwort!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
session_start();
$_SESSION['Email'] = $row[0]['uEmail'];
$resp['redirect'] = "dashboard.php";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
else {
$error[] = "Falsche E-Mail-Adresse!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
And this is my JS part of the login form:
$(function() {
$('#login').click(function(e){
let self = $(this);
e.preventDefault();
self.prop('disabled',true);
var data = $('#login-form').serialize();
$.ajax({
url: '/login2.php',
type: "POST",
data: data,
}).done(function(res) {
res = JSON.parse(res);
if(res['status']) {
location.href = "dashboard.php";
} else {
var errorMessage = "";
console.log(res.msg);
$.each(res['msg'],function(index,message) {
errorMessage += '<p>' + message + '</p>';
});
$("#error-msg").html(errorMessage);
$("#error-msg").show();
self.prop('disabled',false);
}
}).fail(function() {
alert("error");
}).always(function(){
self.prop('disabled',false);
});
});
});
When I try to add action="/login2.php" in the form I get a HTTP 500 Error and the message, that it can not process this request at this time.
I'm not sure if this is your main problem, but it's a significant one. You're preparing two parameters:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
But you're only binding one:
$stmt->execute(array(':email' => $_POST['loginEmail']));
You don't want to include the password in the select, since you're using password_verify() to validate it later. Change your SQL to this:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email";
I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.
Javascript function that sends a string and a number to a php file:
function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
PHP File that takes the string and number and updates a table
<?php
include("config.php");
session_start();
$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}
$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");
$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
?>
How can I retrieve the json_encoded object in the same javascript function?
You'd need a readyState listener to know when the request is done, and then get the data from the responseText
function open_close() {
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status=" + status + "&TicketNum=" + ticketNum;
var http3 = createAjaxRequestObject();
http3.onreadystatechange = function () {
if (http3.readyState == 4) {
if (http3.status == 200) {
console.log(http3.responseText); // <- it's there
}
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
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 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;
}
}
}
}