Ajax window.location not working with PHP login Script - javascript

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.

Related

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

Reading a response in Ajax php and mysql

I can't get the code to work and redirect to 2 different pages depending if the information is correct or not...
So far I have this on my login page:
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'newfile.php',
data: $('#form').serialize(),
success: function (response){
alert(response);
if (success.text="Username or Password incorrect")
window.location.href = "index.php";
else if (success.text="login successful") {
window.location.href = "login_success.html";
} else {
}
}
})
})
and the information Im reading from is (from another page):
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
echo "login successful";
} else {
echo "Username or Password incorrect";
}
$conn->close();
?>
I hope this will work for you try this:
if (response=="usernames or Password incorrect") {
window.location.href = "index.php";
}
else if (response=="login successful")
{
window.location.href = "login_success.html";
}
else { }
Use this code in ajax success. Actually you are using simple ECHO in PHP and using response.text in ajax success.
UPDATE:
you are using = sign for comparing it should be == operator for compare.
UPDATE 2:
i suggest to use status as true false not long string in php like:
if ($result->num_rows >0) {
echo true;
} else {
echo false;
}
Than in ajax response:
if(response == true){
// Success url
}
else {
// failure url
}
The variable success will be undefined inside the success callback function. So the next line will not be executed. So the page will not be redirected. According to your php code , you need to check if response is equal to the corresponding result of not.

data not passed between pages in live server

I came across weird problem with my site only after uploaded it to the live server. In localhost I've no issue with these.
The problem is for login and register function. Let me talk about login first.
I keyed in the credentials and found that the page is called in the f12 network tab.However that page doesn't retrieve any data! So I put aside this jquery/ajax for a while and manually checked the php pages if they return any data but still they don't.
Now the flow like this:
login form filled up by user-> ajax request from php script-> php request from class file and return to ajax -> ajax give access to admin dashboard.
Now as I told you, I excluded ajax request and only checked with php and class file. Again it doesn't return anything from the class file to the php script though I only echoed "something"! Its not even go through any function!
Then I omitted, class file, checked the php script with ajax file.I only echo "wexckdsewndxw" and changed tha datatype in ajax to 'text'..still it doesn't get any value!
So in conclusion, data between pages are not passed at all! SO I suspect its something to do with crossDomain issue as mentioned here:
How does Access-Control-Allow-Origin header work?
But not sure how this works and how I should alter my code.
My code for reference:
login-user.js
/*login user*/
<!--login form submission starts-->
$("document").ready(function(){
$("#login-user").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "login-this-user.php",
data: data,
success: function(data) {
alert(data);
console.log(data);
var i;
for (i = 0; i < data.length; i++)
{
console.log(data[i].email);
console.log(data[i].activate);
console.log(data[i].status);
if($.trim(data[i].status)=='0')
{
//alert("not verified");
$('.invalid-popup-link').trigger('click');
}else
{
//alert("verified");
location.replace("admin/dashboard.php");
}
}//end for
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
return false;
});
});
<!--login form submission ends-->
login-this-user.php
<?php
session_start();
include('config.php');
include('class.login.php');
$return = $_POST;
//$return ='{"email":"admin#gmail.com","pass":"admin","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$status = $login->checkLogin2($data["email"],$data["pass"]);
$_SESSION['user_id']=$status;
$login = new checkLogin();
$profile = $login->check_profile($data["email"]);
$activated_id=array();
foreach($profile as $k=>$v){
array_push($activated_id,array("email"=>$v['email'],"activate"=>$v['activate'],"status"=>'0'));
$_SESSION['email'] = $v['email'];
$_SESSION['activated_id'] = $v['activate'];
}
//header('Content-Type: application/json');
echo json_encode($activated_id);
?>
class
<?php
session_start();
?>
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin2($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT * FROM authsessions WHERE email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$user_id=$row['UUID'];
}
if (password_verify($this->password, $hashAndSalt)==true) {
$status = "verified";
$_SESSION['user_id'] =$user_id;
$_SESSION['logged_in']=1;
}else
{
$status = "not verified";
$_SESSION['user_id'] =0;
$_SESSION['logged_in']=0;
}
return $_SESSION['user_id'] = 1;
}
public function check_profile($param)
{
$this->email = $param;
$sql="SELECT * FROM authsessions WHERE email = '{$this->email}'";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$profile=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$profile[] = $row;
}
return $profile;
}
}
?>

Codeigniter - Create Vote Up system in codeigniter

I am trying to create vote up in my codeigniter named "like". I use this method, that i just found in http://www.technicalkeeda.com/codeigniter-tutorials/voting-system-using-jquery-ajax-and-php-codeigniter-framework
And update is run successfully on database, But the problem is the result of like in view is not showing and the output is text from localhost "Sorry unable to update". And when i refresh the page, the result of "like" showing up.
This is the Controller:
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
$data['id_vote'] = $id_vote;
redirect ('home',$data);
}
This is Model:
function updateUpVote($id_vote){
$sql = "UPDATE vote set like = like+1 WHERE id_vote =?";
$this->db->query($sql, array($id_vote));
return $this->db->affected_rows();
}
Here is the view:
<button class="btn btn-success voteme" id="3_upvote"><span id="<?php echo $data['id_vote']?>_upvote_result" ><?php echo $data['like']?></span> <b>Like</b></button>
This is javascript:
<script type="text/javascript">
$(document).ready(function(){
$(".voteme").click(function() {
var id_vote = this.id;
var upOrDown = id_vote.split('_');
$.ajax({
type: "post",
url: "http://localhost/ngelol/home/voteme",
cache: false,
data:'id_vote='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+id_vote+'_result').text()) + 1;
$("#"+id_vote+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
How to get this result of like without refreshing page?
Many Thanks....
Update:
I have new problem guys, does anyone know how to redirect page in javascript.. I mean, to use vote we need to login first, then i replace
alert('Sorry Unable to update..');
with
url: "localhost/latihan/login"; but it didn't work... thanks for help before
Problem is in your controller function voteme after echoing status you should not use redirect, if you use redirect then it will return your home page html with true status.
So, you can use is_ajax_request(), if ajax request is true then use exit; otherwise redirect() it like,
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// check for ajax request
if(! $this->input->is_ajax_request()){ // if not ajax request
$data['id_vote'] = $id_vote;
redirect ('home',$data);// redirect it
}
exit;
}
Even your referral link is not using redirect()
Try this:
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
return $status
}
To redirect with javascript, you can use 'window.location.href' :
window.location.href = "localhost/latihan/login";

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