make a deactivate account with jquery, ajax and php prob - javascript

I am adding a deactivate feature on a website i am working on, so I added a form with a textarea to tell the reason why the user is deactivating his account and a button that become enabled when the textarea is filled out so I sent the call via jquery ajax to a php script which will update the users_table in the database to 1 for deactivated then must log the user out and redirect them to the index page of the website. So everything works fine except the log out it is not happening and no redirect. I need help with that please
here is my php script :
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
$user_id = (int)$_SESSION["user_id"];
if(isset($_POST['deactivate_reason'])) {
$deactivate_reason = mysql_prep($_POST['deactivate_reason']);
// INSERT into table
$query1 = "INSERT INTO deactivate_reason_table ( ";
$query1 .= "user_id, reason";
$query1 .= ") VALUES (";
$query1 .= " $user_id, '$deactivate_reason'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
$confirm_query1 = confirm_query($result1);
// if query1 is successful and replies deleted then we make the second query to delete the board comments
if ($confirm_query1 == 0) {
echo "error";
exit();
} else {
// UPDATE table
$query2 = "UPDATE users_table ";
$query2 .= "SET deactivated = 1";
$query2 .= "WHERE user_id = $user_id";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if ($confirm_query2 == 0) {
echo "error";
exit();
} else {
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
// redirect_to() is a custom function in the functions.php that redirects
redirect_to("../index.php");
}
}
}
and here is my jquery ajax script :
$(document).on("click", "#deactivate_button", function(e){
e.preventDefault();
var text = $("#deactivate_reason_textarea").val();
var url = "widgets/deactivate.php";
$.ajax({
url: url,
method: "POST",
data: {
deactivate_reason: text
},
beforeSend: function() {
CustomSending("Processing...");
},
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
}
});
});

To redirect the user for a another page in PHP you can use something like header('Location: ...') (manual), but you are calling the script in ajax, then you need to put the redirect in this, not in the called PHP script.
To redirect in JavaScript you can use window.location (tutorial).
window.location = "my/another/script.php";
In your case, you need to put it in the success of ajax.
$.ajax({
... # your occulted script
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
window.location = "another/script.php";
// or you can put it in a timeout to show a message for the user or other thing
// setTimeout(function() {
// window.location = "another/script.php";
// }, 10000);
}
});

ok guys thanks a lot for your help, I managed to solve this with your help
after i added widow.location = "insert.php" like tadeubarbosa suggested then i went to my index.php page and added these lines :
if (logged_in()) {
$email = $user_data['email'];
$id = $user_data['user_id'];
$edited = account_edited($email);
if ($edited == 0){
redirect_to("editprofile.php?id=$id");
}
$is_deactivated = is_deactivated($_SESSION['user_id']);
if ($is_deactivated == 1) {
$query = "UPDATE users_table SET online = 0 WHERE user_id = $id";
$result = mysqli_query($connection, $query);
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
redirect_to("index.php");
}
}
then went to the login.php script and added a query to update deactivated = 0 if the user logs in so the account reactivates

Related

Ajax window.location not working with PHP login Script

I have a PHP login script which executes with ajax. The ajax request now starts the session in the login successfully but the window.location function doesn't work (doesn't redirect to exporter.php) in the ajax request. Below are my codes.
php Login Script
if(isset($_POST['log_name']) && isset($_POST['log_password'])) {
$username = $_POST['log_name'];
$password = $_POST['log_password'];
$sql = $db->prepare("SELECT * FROM users WHERE uname = ?");
$sql->bindParam(1, $username, SQLITE3_TEXT);
$ret = $sql->execute();
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$id = $row['userid'];
$regas = $row['regas'];
$uemail = $row['uemail'];
$pword = $row['pword'];
$uname = $row['uname'];
$package = $row['package'];
if (password_verify($password, $pword))
{
$_SESSION['log_id'] = $id;
$_SESSION['log_name'] = $username;
$_SESSION['regas'] = $regas;
$_SESSION['uemail'] = $uemail;
$_SESSION['package'] = $package;
//header("Location: index.php?log_id=$id");
//echo "Sigining In...";
//die("<script>window.location='exporter.php?userid={$id}';</script>");
exit();
}
else
{
echo "Information incorrect";
exit();
}
}
}
Ajax Request
$("#submit_log").click(function() {
//e.preventDefault();
username=$("#log_name").val();
password=$("#log_password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "log_name="+username+"&log_password="+password,
success: function(html){
if(html=='true') {
window.location.assign = "exporter.php";
}
else {
$(".logresult").html('Incorrect Username and Password');
}
},
beforeSend:function()
{
$(".logresult").html("Loading...")
}
});
return false;
});
Beginning part of exporter.php
session_start();
require_once ("db.php");
$db = new MyDB();
if (!isset($_SESSION['log_name']) || !isset($_SESSION['log_id']) || !isset($_SESSION['regas']))
{
header("Location: index.php");
}
What could be wrong here and how do i fix this redirecting issue please!!!.Thanks.
your php login script needs echo 'true'; according to your ajax callback.
and use location.href = "/exporter.php"; to redirect page with JavaScript
You should use like this:
window.location.href= "/exporter.php";
window.location.assign = "exporter.php";
will not work, use
window.location = "exporter.php";
You are using assign incorrectly.
window.location.assign("exporter.php")
Or you can use href instead.
window.location.href = "exporter.php";
Try using assign like this:
window.location.assign(data);
if this method not work for you let me know.
and if the Success:html is boolean then you're checking it in wrong way delete the single quotes it's not a string it is boolean datatype.

PHP Header redirect not working anymore when i use event.preventDefault() on submit

my PHP code was working fine until I decided to use jquery for my signup page to handle and check the fields, it's working there is no error, everything is submitted to the server correctly so there is no problem with the code PHP nor jquery, but the header("location: ../****.php") no longer send me to another page after I hit submit, instead it loads the new page on top of the old one without refreshing.
This is my jquery code for the signup page:
<script>
$(document).ready(function() {
$("#myForm").submit(function(event){
event.preventDefault();
var username = $("#signup-username").val();
var pwd = $("#signup-pwd").val();
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
});
});
</script>
and this is my PHP code in my include page:
<?php
if (isset($_POST['submit'])){
include_once 'dbh.inc.php';
$username= mysqli_real_escape_string($conn, $_POST['username']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = $errorValid = false;
if(empty($username)|| empty($pwd)){
echo "Fill in all Fields!";
$errorEmpty = true;
}
else{
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uid);
$uid = $username;
$stmt->execute();
$result = $stmt->get_result();
$usernamecheck = mysqli_num_rows($result); // check if the results
$rowNum = $result->num_rows;
if($rowNum > 0){
echo "Username is taken!";
$errorValid = true;
}
else{
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, pwd) VALUES (?, ?)");
$stmt->bind_param("ss",$uid, $password);
$uid = $username;
$password = $hashedPwd;
$stmt->execute();
$result = $stmt->get_result();
header("location: ../user-login.php");
}
}
}else{
header("location: ../user-signup.php");
exit();
}
?>
<script>
$("#signup-username, #signup-pwd").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorValid = "<?php echo $errorValid; ?>";
if (errorEmpty == true $$ errorValid == true){
$("#signup-username, #signup-pwd").addClass("input-error");
if (errorFEmpty == false && errorValid == false){
$("#signup-username, #signup-pwd,").val("");
}
</script>
how do I fix this?
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
When the above code gets to the point where header("Location: file.php");
It'll fetch that file into $(".form-message")
To Avoid this you can use ajax to post data and javascript inbuilt redirection
$.ajax({
type: "POST",
url: "includes/user-signup.inc.php",
data: "username="+ username +"&pwd="+ pwd,
success: function(data) {
window.location.href = "../****.php";
}
});
Hope this answer was helpful.
Your code operates exactly as it should.
$(document).ready(function() {
$("#myForm").submit(function(event){
// THIS LINE RIGHT HERE
event.preventDefault();
******************
$(".form-message").load("includes/user-signup.inc.php",{
******************
});
});
});
Event prevent default stops the redirect action. Additionally you then use jquery to load the contents of the file into the DOM element with the class:
.form-message
Remove event.preventDefault();

Sessions in AngularJS and PHP application

I have an AngularJS application that I am updating to use PHP 7. Currently I have a custom session handler setup for sessions:
Custom Session Handler (session.php)
function sess_open( $path, $name ) {
return true;
}
function sess_close( ) {
$sessionId = session_id();
return true;
}
function sess_read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
return $data;
}
function sess_write( $id, $data ) {
$db = dbConn::getConnection();
$tstData = sess_read( $id );
if (!is_null($tstData)) {
// if it does then do an update
$stmt = "UPDATE session SET session_data =" . $db->quote($data) . " WHERE session_id=" . $db->quote($id);
$db->query($stmt);
}
else {
// else do an insert
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ")";
$db->query($stmt);
}
return true;
}
function sess_destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
return $db->query($stmt);
}
function sess_gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
return $db->query($stmt);
}
session_name('PROJECT_CUPSAW_WEB_APP');
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
ob_flush();
In my app.js I have a continuous check to see if the user is authenticated and can access the application.
App.js
/*
* Continuous check for authenticated permission to access application and route
*/
app.run(function($rootScope, $state, authenticationService, ngToast) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
authenticationService.isAuthenticated()
.success(function () {
if(toState.permissions) {
ngToast.dismiss();
event.preventDefault();
$state.go("logout"); // NEEDS TO CHANGE - Unauthorized access view
return;
}
})
.error(function () {
ngToast.dismiss();
event.preventDefault();
localStorage.clear();
$state.go("authentication"); // User is not authenticated; return to login view
return;
});
ngToast.dismiss();
});
});
In the code above, isAuthenticated runs isUserAuthorized.php
isAuthenticated
/*
* Check if user is authenticated; set role/permissions
*/
this.isAuthenticated = function() {
return $http.post(baseUrl + '/isUserAuthorized.php');
};
isUserAuthorized.php
<?php
require_once 'session.php';
// Check to ensure user is authenticated to initiate request
if (array_key_exists('authenticated', $_SESSION) && $_SESSION['authenticated']) {
return http_response_code(200);
} else {
// Clear out all cookies and destroy session
if( array_key_exists('HTTP_COOKIE', $_SERVER)){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
session_destroy();
return http_response_code(401);
}
The session should be started when session.php is required. It appears that this is not happening though. Upon accessing the application, the login page is displayed, but isUserAuthorized.php is throwing a warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
When I select the Login button, login.php is called, but the user gets brought right into the application, despite incorrect credentials.
login.php
<?php
require_once '../database.php';
require_once 'session.php';
require_once 'ldap.php';
$_SESSION['authenticated'] = false;
//$conn = connect_db();
try {
$data = json_decode(file_get_contents('php://input'));
$username = strtolower($data->username);
$password = $data->password;
// Check domain credentials; return user token if verified
if(ldap_authenticate($username, $password)) {
$_SESSION['authenticated'] = true;
}
else {
echo('Invalid username and/or password!');
return http_response_code(400);
}
}
catch(PDOException $e) {
return http_response_code(400);
}
I'm not entirely sure what's causing this odd behavior, and why the session isn't being created. Do I need to explicitly call the sess_write function?
Update
I discovered that removing the require_once 'session.php' from login.php causes the proper behavior. The user is able to login when they provide valid credentials. However, the session data is still never being written to the database. Any idea why?
The issues came down to my session handler. As of PHP 7, the sess_read function must return a string. This was causing the warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
I fixed this by returning '' when $data was null.
This caused issues with my sess_write function knowing when to insert and when to update. I fixed this by changing the SQL.
Ultimately I ended up making the session handler a class, as shown in the final result:
<?php
require_once ('../database.php');
class CustomSessionHandler implements SessionHandlerInterface{
public function open( $path, $name ) {
return true;
}
public function close( ) {
return true;
}
public function read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
if(!$data){
return '';
}
return $data;
}
public function write( $id, $data ) {
$db = dbConn::getConnection();
//Works with Postgres >= 9.5
//$stmt = "INSERT INTO session (session_id, session_data) VALUES (" . $db->quote($id) . ", " . $db->quote($data) . ") ON CONFLICT (session_id) DO UPDATE SET session_data=" . $db->quote($data) . ";";
//Works with Postgres < 9.5
$stmt = "UPDATE session SET session_data=" . $db->quote($data) . " WHERE session_id=" . $db->quote($id) . ";";
$db->query($stmt);
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ");";
$db->query($stmt);
return true;
}
public function destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
$data = $db->query($stmt);
return true;
}
public function gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
$data = $db->query($stmt);
return true;
}
}
session_name('PROJECT_CUPSAW_WEB_APP');
$handler = new CustomSessionHandler();
session_set_save_handler($handler, false);
session_start();
ob_flush();

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources