i have a login script that uses AJAX, but i have a problem with the code that i cannot work out.
Here is the code:
JS:
$(document).ready(function(){
$("#loginForm").submit(function(){
$("#report").removeClass().addClass('loader').html('Loading...').fadeIn(1000);
$.post("check_login.php",{ username:$('#signin_username').val(),password:$('#signin_pwd').val()},function(data){
console.log(data);
if(data == "TRUE"){
document.write(data);
console.log("YEP");
$("#report").fadeTo(200,1,function(){
$(this).html('Logging in.....').addClass('log').fadeTo(900,1,function(){
document.location='members/index.php';
});
});
}
else if(data == "FALSE"){
console.log("NOPE")
$("#report").fadeTo(200,1,function(){
$(this).html('Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
FORM:
<div id="login_form">
<h3>Login</h3>
<div id="signup_link">
Signup Now
</div>
<div id="report"></div>
<form action="" method="post" id="loginForm">
<ul>
<li>
<label for="username">Email: </label>
<input type="text" id="signin_username" name="signin_username" required="required" />
</li>
<li>
<label for="pwd">Password: </label>
<input type="password" id ="signin_pwd" name="signin_pwd" required="required" />
</li>
<li>
<input type="submit" name="login" id="login" value="Login"/>
</li>
<li>Forgot Password</li>
</ul>
</form>
</div>
and PHP file called by js:
require_once 'members/classes/Membership.php';
# Make instance of membership class
$membership = new Membership();
$true = "FALSE";
$false = "FALSE";
if(!empty($_POST))
{
$username = $_POST['username'];
$pwd = $_POST['password'];
if($test = $membership->validate_user($username, $pwd))
echo $true;
else
echo $false;
}
else
{
echo "Details werent entered";
}
Basically the method the php script is calling checks the database to see if the users details match and if they're allowed to login, if so returns true if not returns false (These are the only two values it will return.
So it works file until we get back into the js code, note the first "console.log" the output of this seems to have loads of white space before the word that im looking for something like this:
"
TRUE"
The space above the true is nothing so when i test if(data == "TRUE") it's never true.
Either something strange is happening or i'm missing something really silly. Can anyone see whats wrong?
Thanks for the time.
Make sure you haven't got any include files that are outputting whitespace. It's easy to make that mistake.
Related
Good day.
Trying to create a checkbox (materialize switch), which, if you change it, submits the form. The problem is, that it returns the value as $_POST['statusValue'] ONLY if its originally not checked, if it is - returns null.
Any ideas?
<div class="switch">
<form method="post">
<label style="font-size: 10px">
Off
<input type="checkbox" value="<?php echo $q->questionnaire->questionnaire_id?>" name="statusValue" id="statusValue" onclick='this.form.submit()' <?php echo $q->questionnaire->questionnaire_status == 1 ? 'checked="checked"' : '';?»
<span class="lever"></span>
On
</label>
</form>
</div>
Your question is not clear. I guess what you are trying to achieve in check if the checkbox on the HTML was checked or not by the user.
Below, I wrote you a simple code of how achieving that. After submitting the form the $statusValue variable will contain either "checked" or "not checked" depending on what the user did on the HTML page.
In your HTML (frontend):
<div class="switch">
<form method="post">
<label style="font-size: 10px">
<input type="checkbox" name="statusValue" onChange="this.form.submit()" />
<span class="lever"></span>
</label>
</form>
</div>
In your php (backend):
<?php
isset($_POST['statusValue'])
$statusValue = "checked";
else
$statusValue = "not checked";
?>
If I misunderstood you, comment here so I can help you further.
In this html code I create a function that has two parameters id and status that will pass throught it.
<div class="switch">
<form method="post">
<label style="font-size: 10px">
Off
<input type="checkbox" value="<?php echo $q->questionnaire->questionnaire_id?>" name="statusValue" id="statusValue" onclick="changeStatus('<?php echo $q->questionnaire->questionnaire_id ?>,'<?php echo $q->questionnaire->questionnaire_status ?>')" <?php echo $q->questionnaire->questionnaire_status == 1 ? 'checked="checked"' : '';?»
<span class="lever"></span>
On
</label>
</form>
</div>
Invoking the function changeStatus using Ajax function and avoiding to refresh the page in that time, you press the switch.
<script>
function changeStatus(id,status){
if(habilitado==2) {
var url = 'admin/funciones/desbloquearUsuario.php';
$.ajax({
type:'POST',
url:url,
data:{idUser:id},
error:function(){
alert("It coudn't be disabled");
}
});
}else {
var url = 'admin/funciones/bloquearUsuario.php';
$.ajax({
type: 'POST',
url:url,
data:{idUser:id},
error:function(){
alert("it couldn't be blocked");
}
});
}
}
}
</script>
For this php file desbloquear.php I unblock Users setting value 1
require_once "../../funciones/conexion.php" ;
conexion();
$idUser = $_POST['idUser'];
$habilita = 'UPDATE public."USUARIO" SET "Habilitado"=\'1\' WHERE
"ID"=\''.$idUser.'\'';
pg_query($habilita);
In your php code you can use this. Well in this case, in this php file I block users with the value 2 in my BD
<?php
require_once "../../funciones/conexion.php";
conexion();
$idUser = $_POST['idUser'];
$deshabilita = 'UPDATE public."USUARIO" SET "Habilitado"=\'2\' WHERE
"ID"=\''.$idUser.'\'';
pg_query($deshabilita);
This is my login form:
<div class="form-container">
<h1 style="text-align:left">Login Here!</h1><br>
<form class="form-horizontal" action="<?php echo base_url(); ?>index.php/User_Authentication_Controller/login_user" method="POST">
<div class="error_msg1"></div>
<input autofocus="autofocus" type="text" name="txt_login_username" class="form-control" placeholder="Username.."/><div class="error_msg2"></div>
<input type="password" name="txt_login_password" class="form-control" placeholder="Password.." /><div class="error_msg3"></div>
<center><button class="btn btn-info" type="submit">Login</button><br/><br/>
Forgot Password?</center>
</form>
</div>
This is my controller:
public function login_user(){
$username = $this->input->post('txt_login_username');
$password = md5($this->input->post('txt_login_password'));
$result=$this->LogIn_Model->login($username,$password);
if (!empty($username) && !empty($password)) {
if($result!=null){
$_SESSION["username"] = $username;
$_SESSION["id"] = $result["0"]["Account_no"];
$_SESSION["Usertype"] = $result["0"]["Usertype"];
if($result["0"]["Status"] == 1){
if($result["0"]["Usertype"] == 0){
redirect('User_Authentication_Controller');
}
else if($result["0"]["Usertype"] == 1){
redirect('Pages_Controller/show_adminpage/');
}
}
else if($result["0"]["Status"] == 0){
redirect('User_Authentication_Controller');
}
}
else{
redirect('User_Authentication_Controller');
}
}
else{
redirect('User_Authentication_Controller');
}
}
This actually works!
Now my question is:
As you see in the else if($result["0"]["Status"] == 0){}, all I want is that after I submitted the page it will redirect back to the login, and I want that the
<div class="error_msg1"></div>
will show an error telling, "Your account has been deactivated by the Admin" And if he inputs a username it will stay still as he submit it! how will I do that? If he inputs Username: Michael and Inputs a wrong password, I want the Username: Michael to stay still! How will I do that after the form submit?
you can use set_userdata to store error msg and can show:
in your controller:
else if($result["0"]["Status"] == 0){
$this->session->set_flashdata('error_msg1','Some Error Msg!');
}
and in your view:
<?php if($this->session->flashdata('error_msg1')) : ?>
<div class="alert alert-success">
<span class="alert-rr">
<i class="fa fa-check-circle" aria-hidden="true"></i>
</span>
<span class="alert-msg">
<?php echo $this->session->flashdata('error_msg1'); ?>
</span>
</div>
<?php endif; ?>
Way 1
Use AJAX instead of form. Your js make an ajax post to your server, and then get the result. Depending on it, your js reacts, for example, showing error messages. This is a good choice.
Way 2
For example, you can set $_SESSION['ShowErrorMsg1']=true in login_user, then in your login page php, just say:
.
if(isset($_SESSION['ShowErrorMsg1']) && $_SESSION['ShowErrorMsg1']==true){
echo '<div class="error_msg1"></div>';
}
then the error msg will be shown.
UPDATE:
The main idea is that you can storage anything you want to pass it from one php to another php in $_SESSION. If you want to pass on $msg_content for example, just use $_SESSION['somekey']=$msg_content; in one php. Then in another php use $_SESSION['somekey'] who storages the data of $msg_content.
I have 'cloned' a script, except for the variables the script is exactly the same as the original! But it just doesn't entirely work. it get stuck at:
if(validConnection=="")
{
$('#UsernameConnection').css('border-color','#00ff00');
$('.ErrorUsernameConnection').text('');
checkUsername1 = true;
}
(the rest of the code is below)
I have been checking if I made some mistake in changing the varables but they all seem to match properly. What is wrong? How comes it work fine just with different variables and not this time???
Here is the HTML:
<div id="Connection">
<div class="Connection">
Connection
<strong>×</strong>
</div>
<?php connection(); ?>
<div class="formConnection">
<form method="POST" autocomplete="off" name="Connection">
<label for="Connection">Username:</label><br/>
<input type="text" name="UsernameConnection" id="UsernameConnection"/><br/>
<span class="ErrorUsernameConnection"></span><br/>
<label for="Connection">Password:</label><br/>
<input type="password" name="PasswordConnection" id="PasswordConnection"/>
<span class="ErrorPasswordConnection"></span><br/>
<input type="checkbox" name="checkbox"/><label>Remember me</label><br/>
<input type="submit" name="Connection" value="Log In" id="Connection" class="LogIn"/>
</form>
</div>
Here is the php:
<?php
if(isset($_POST['UsernameConnection']))
{
$Username1 = $_POST['UsernameConnection'];
if(preg_match("/^([a-zA-Z0-9àáâãäåçèéêëìíîïðòóôõöùúûüýÿ]{1,}[._-\s]?)+[a-zA-Z0-9àáâãäåçèéêëìíîïðòóôõöùúûüýÿ]{1,}$/",$Username1))
{
echo "";
}else
{
echo "Invalid";
}
}
?>
and JS:
$(document).ready(function(){
var checkUsername1 = false;
$('#UsernameConnection').keyup(function(){
var Username1 = $('#UsernameConnection').val();
if(Username1=="")
{
$('#UsernameConnection').css('border-color','red');
$('.ErrorUsernameConnection').text('Error message 1');
checkUsername1 = "Username empty";
}else
{
$.post('fonctions/validUsernameConnection.php',{Username1:Username1},function(validConnection)
{
$('.ErrorUsernameConnection').text(validConnection);
if(validConnection=="")
{
$('#UsernameConnection').css('border-color','#00ff00');
$('.ErrorUsernameConnection').text('');
checkUsername1 = true;
}else
{
$('#UsernameConnection').css('border-color','orange');
checkUsername1 = "Username Invalid";
}
});
}
});
});
PS: I'm a little bit lost with all the stack's sites so forgive me if this isn't the right one to post this =/
the problems seems to be with this line
$.post('fonctions/validUsernameConnection.php',{Username1:Username1},
function(validConnection)
In your PHP you should check for $_POST['Username1'] instead of $_POST['UsernameConnection']
OK...i have something which makes no logical sense and I hope someone can point out the silly mistake I am making. I have a page in which i want the menus to change whether a user is logged in or not. I am using a session variable $_SESSION['is_logged_in] to store the logged in status. So for example, if logged out, the menu should say login. If logged in, the same menu should say logged out. Here is the code in logical pieces. I apologize in advance for all the code snippets but I want to be as clear as possible. Please help!
First, i have the main page called index.php which has some empty divs:
<div id="wrapper">
<div id="header">
<h1>My Page</h1>
<div id="navigation">
</div> <!-- end of navigation div -->
</div> <!-- end if header div -->
<p> </p>
<div id="mainContent">
</div><!-- end mainContent div -->
</div> <!-- end wrapper div -->
In this page (index.php), i have a jquery load of the navigation div on document ready:
<script type="text/javascript">
$(document).ready(function(e) {
//load the default menu
$('#navigation').load("menu.php");
});
</script>
OK...now menu.php has the following html/php:
<?php
session_start();
include 'php/functions.php';
//following is for debugging, you will see later where this is useful
if (is_logged_in())
{
echo "logged in value: " . is_logged_in() . "<br />";
print_r($_SESSION);
}
else
echo "not sure what is going on</br >";
echo "<br />";
?>
<ul id="menu" class="DropdownMenu">
<li class="sub">Account
<ul>
<?php
//this is where it should show one link or the other based on the value in $_SESSION
if (is_logged_in()) {
echo "<li>Log Out</li>\n";
} else {
echo "<li>Log In</li>\n";
}
?>
</ul>
</li>
</ul>
Ok...at this point, when the page loads, on top of the menu i see the debug message "not sure what is going on here" as expected because i am not logged in yet. Then I click on the Login link and via ajax, it populates the mainContent div in the index.php:
This is in menu.php:
$(document).ready(function(e) {
var options = {
target: '#mainContent', // target element(s) to be updated with server response
success: reloadMenu, // post-submit callback
delegation: true
};
// post-submit callback
function reloadMenu(responseText, statusText, xhr, $form) {
$('#navigation').load("menu.php");
};
//set the jquery form plugin for the login form
$('.ContentForm').ajaxForm(options);
//load the login form in the mainContent div
$('#wrapper').on("click", ".ClickLogin", function(e) {
$('#mainContent').load("login.php");
});
});
The above code shows that when the form is submitted, on success, the post submit callback should be re-loading the menu just like the initial load on the index.php document ready. With debugging, i do see that the it does reload it, but it never sees anything in the session variables so even though i am logged in, it still shows the Login link instead of log out.
Now, bringing it all together just to show i am not crazy, here is what is in the login.php:
<?php
// start the session
session_start();
include 'php/functions.php';
//this sections handles the post of the form
$show_form = true;
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$email = $_POST['email'];
$password = $_POST['password'];
if (authenticate_user($email, $password)) //this will set $_SESSION variables
{
$show_form = false;
echo "Congratulations " . get_user_name() . ", you are logged in <br />";
//following is for debugging, you will see later where this is useful
if (is_logged_in())
{
echo "logged in value: " . is_logged_in() . "<br />";
print_r($_SESSION);
}
else
echo "not sure what is going on</br >";
}
else
{
echo "Invalid email or password. Try again <br />";
}
}
?>
<?php if ($show_form) { ?>
<div id="formContent">
<h2 class="ContentHeader">Log In</h2>
<form id="contentForm" name="registration" class="ContentForm" method="post" action=<?php echo $_SERVER['PHP_SELF']?>>
<p>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required="required">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required="required">
</p>
<p>
<input type="submit" name="insert" id="insertLink" value="Submit It" />
<input type="reset" name="cancel" id="cancel" value="Reset" />
</p>
<p>Forgot Password? Click here</p>
<p>Need to Register? Click <a class="ClickRegister" href="#">here</a></p>
</form>
I know it is a lot of code so i want to point out one thing. At this point, when the form is submitted, in the #navigation div, the menu.php is reloaded and in the #mainContent div, the login.php is reloaded. Both are executing this exact same code:
//following is for debugging, you will see later where this is useful
if (is_logged_in())
{
echo "logged in value: " . is_logged_in() . "<br />";
print_r($_SESSION);
}
else
echo "not sure what is going on</br >";
When the page displays after the login form submit, above the menu it says "not sure what is going on" followed by "Array()", however in the mainContent, it shows "logged in value: 1" and prints out all the session values.
Just for completeness, the is_logged_in() function looks like this:
//return true if the current session is logged in
function is_logged_in()
{
if (array_key_exists('is_logged_in', $_SESSION))
return $_SESSION['is_logged_in'];
}
I have session_start() in both menu.php and login.php, if i didn't it gives me all sorts of other errors when trying to access the $_SESSION array.
I really hope someone can spot my mistake. Please help!
Thanks in advance.
Answering the question officially for closure. As mentioned in the comments above, I was destroying the session prior to setting it as part of the login. I am still not sure why that had the effect it did since both divs were loaded after the destroy/re-create but maybe there is some ajax race condition.
I am just glad it is solved and I can move on. Thanks to all for your input.
This is pretty specific and I have not found an answer yet.
I am writing a script to check if a name is already input into the SQL server using JQuery $.POST.
The front end looks like this:
register.php
<div id="container" class="container">
<div id="wrapper" class="wrapper">
<div id="title" class="title">
Welcome to Taskar!
</div>
<div id="login" class="login">
<form method="post" action="registermembers.php">
<div id="exists">
Register Your Company Below:
</div>
<input type="text" id="company" name="company" value="Company Name"/> <br />
<br />
<input type="text" id="password" name="password" value="Default Password"/> <br />
<input type="submit" name="submitcompany" value="Submit" />
</form>
<script>
$(document).ready(function() {
$('#company').keyup(function() {
var $company = $(this).val();
var $reg = $('#exists').html();
$.post('include/reg_post.php', { company: $company, reg: $reg }, function(company) {
$('#exists').html(company);
});
});
});
</script>
</div>
</div>
</div>
The backend code looks like this:
reg_post.php
<?php
include 'include/db.php';
$reg = $_POST['reg'];
$company = $_POST['company'];
$email_hash = $_COOKIE['email_hash'];
$password = $_COOKIE['password'];
$sql = "SELECT * FROM taskar_employee WHERE (company = '$company')";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
} ?>
Now, the problem I am having is, when I am testing this, it works fine all the way up to when I type in a company name that is in the database. It shows me that the company is already registered. When I press backspace or type another letter, it still tells me the company still exists, though it obviously would not.
It seems that the if statement wants to stop the $.post feature from continuing after it gets the opposite statement?
What do you guys think?
Your problem lies in the way you're using your $reg variable.
$reg contains the HTML contents of the #exists div, so it's "Register your Company Below:" to begin with. But, once you've hit a company name that does exist, you replace that HTML with "This Company Already Exists!". From that point on, $reg, on both the JavaScript and PHP sides, is always "This Company Already Exists!" (since you always pass $reg in your POST).
It would probably be much easier if the contents of that div weren't passed to or handled by the PHP code at all. It'd be simpler if your PHP script just returned "1" if the company existed, and "0" if not (or some other equally simple flags).
Then, on the JavaScript side, you could just do:
$.post('include/reg_post.php', { company: $company }, function(exists) {
var message;
if (exists === '1') {
message = 'This Company Already Exists!';
}
else {
message = 'Register Your Company Below:';
}
$('#exists').html(message);
});
You're passing $('#exists').html(); to be returned in the event that the company is not found. The problem is, in the event that the company is found, you replace the html within #exists. Then the next time you call the post you pass this text back along so in this case:
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
}
your $reg is now set to This Company Already Exists! so regardless of what happens you're going to return that text.