Is it possible to make codeigniter not to redirect after a failed login attempt and show a message on the same login box.
My login box is a popup type, which appears after I have clicked on the login button and disappears after clicking on the background.
Controllers
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run()){
$data=array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('site/members');
}else {
$this->main();
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
}
I was trying to change elses with error messages but it still redirected to another page.
Html:
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
<script>
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>site/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password").val()
},
success: function(response) {
if(response == 'success'){
location.href = 'site/members';
} else {
$("#errors").show();
}
}
});
}
</script>
If you want to have the alert in the modal, you'll want to check the data with ajax (javascript or jquery). For example you'd have something like this:
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>your_controller/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password).val()
},
success: function(response) {
if(response == 'success'){
location.href = <where you want to send them>;
} else {
$("#errors").show();
}
}
});
}
And your HTML would look something like:
<div class="hide" id="errors">Incorrect username/password.</div>
<input type="email" id="email" />
<input type="password" id="password" />
The class="hide" is meant to be something CSS related where you would have something like "display: none;".
Then in your controller you'd check like this:
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
The echoed response is what will be sent to your ajax success function.
Edit:
You need to not use the form submission for the above to work, because with that method we don't want to submit the form, we want to pass the data from it.
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
I've also changed the javascript function above to be viewed as a function.
use
window.location.href = '/redirectpage'
Related
<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.
I got to build a log in form on restricted-country.tpl to access my website.
The form and the ajax call work great but it's impossible to call the php script 'cause a 503 error due to geolocation.
The script is in "controllers/front/".
Anybody knows how to grant access to the script or knows an area where I could put it and access it passing through the 503?
Or maybe call it in an other way?
(It's important that the log in form use Geolocation by ip)
Here is the form :
<form class="form-signin col-xs-12 col-md-6 col-sm-12" id="everaccess_form">
<label for="password" style="color:#FFF;">{l s='Mot de passe'}</label><br/>
<input type="text" id="login" name="login" class="form-control" placeholder="Identifiant" required>
<input type="password" id="password" name="password" class="form-control" placeholder="Mot de passe" required>
<input type="hidden" id="IP" name="IP" class="form-control" value="">
<input type="hidden" id="shop" name="shop" class="form-control" value="{$cart->id_shop}">
<input class="btn btn-primary btn-block" type="submit" style="width:22.5%;" value="{l s='Se connecter'}" />
<br/><hr>
</form>
Here is the ajax call :
form.submit(function(e) {
$.ajax({
type: 'POST',
url: path_url+'/controllers/front/verif.php',
data: form.serialize(),
dataType: 'json',
success: function(jsonData) {
if (jsonData == 'OK'){
console.log('Correct logins');
location.reload();
} else {
console.log(jsonData);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
e.preventDefault();
});
Here is the script :
if (Tools::getIsset('password') || Tools::getIsset('login') || Tools::getIsset('IP') || Tools::getIsset('shop')) {
$password = Tools::getValue('password');
$login = Tools::getValue('login');
$allowedUsers = EverCommission::getAllAgentLogin();
foreach ($allowedUsers as $user => $mail) {
$users[$user] = $mail['email'];
}
if ($password == Configuration::get('EVERCOM_COM_PASS') && in_array($login, $users)) {
//Separator
$separator = "\n";
$idShop = Tools::getValue('shop');
//Geolocalisation whitelist
$whitelist = Configuration::get('PS_GEOLOCATION_WHITELIST');
$WhiteListIp = Tools::getValue('IP');
$New_WhiteList = $whitelist . $separator . $WhiteListIp;
//Temp whitelist
$Old_Temp_WhiteList = Configuration::get('PS_TEMP_WHITELIST');
$New_Temp_WhiteList = $Old_Temp_WhiteList . $separator . $WhiteListIp;
//Updating values
Configuration::updateValue('PS_TEMP_WHITELIST', $New_Temp_WhiteList);
Configuration::updateValue('PS_GEOLOCATION_WHITELIST', $New_WhiteList, false, null, $idShop);
Configuration::updateValue('PS_GEOLOCATION_WHITELIST', $New_WhiteList, false, null, 'NULL');
$return = 'OK';
} else {
$return = 'Wrong';
}
echo Tools::jsonEncode($return);
} else {
$return = 'ID or Password not set using Ajax';
echo Tools::jsonEncode($return);
}
Thank you very much.
Since your ajax call returns Error: temporarily overloaded, you might have a memory_limit problem on your configuration.
Open your shop BackOffice
Go to advanced parameters > Informations
Check that the memory limit is over or equal to 128M
If the memory_limit is lower. You should edit your php.ini file.
I have the simple task of validating a user has entered the first name. This is working in most browsers but chrome doesn't seem to be getting a response from ajaxfirstname.php. Here is the script:
jQuery(document).ready(function () {
var validatefirst_name = jQuery('#validatefirst_name');
jQuery('#first_name').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefirst_name.removeClass('error').html('<span style="margin-left: 5px;"><img src="images/loader.gif" height="16" width="16" /></span>');
this.timer = setTimeout(function () {
jQuery.ajax({
url: "ajaxfirstname.php",
data: "action=check_first_name&first_name=" + t.value,
dataType: "json",
async: false,
type: "post",
success: function (j) {
validatefirst_name.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
and my html
<label for="first_name">First Name</label>
<input id="first_name" name="first_name" type="text" id="first_name" value="<?php
$name = explode(' ',$this->my->name);
echo $name[0];
?>">
<span id="validatefirst_name"></span>
I opened up the developer tool but I don't see any error on this particular script. Does anyone have suggestions on this? Does the above code look correct? Would Chrome have any issues with it? Thanks in advance.
May be its because you have used id in textbox twice ["id="first_name"].Please change this and let me know..
id="first_name" name="first_name" type="text" id="first_name" value="my->name);
I am trying to build a custom wordpress ajax login form but I can't get it sorted. Here is the codes I use:
HTML:
<form class="well form-inline" id="login">
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#loginButton").click(function() {
var username = $('#loginUsername').val();
var password = $('#loginPassword').val();
var rememberme = "forever";
var redirect = '<?php bloginfo('url'); ?>';
var data = {
user_login: username,
user_password: password,
remember: rememberme,
redirect_to: redirect
}
$.ajax({
url: '<?php bloginfo('url'); ?>/wp-login.php',
data: data,
type: 'GET',
dataType: 'jsonp',
success: function( result ) {
if (result.success==1) {
alert("Ok!");
} else {
alert("Not Ok!");
}
}
});
});
});
</script> <!-- Login Script --->
Can someone tell me what am I doing wrong here?
WordPress: Simple Ajax Login Form
<form id="login" action="login" method="post">
<h1>Site Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username">
<label for="password">Password</label>
<input id="password" type="password" name="password">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<input class="submit_button" type="submit" value="Login" name="submit">
<a class="close" href="">(close)</a>
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
--
<?php
//add this within functions.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
Create a file ajax-login-script.js within theme's directory and paste this js
jQuery(document).ready(function($) {
// Show the login dialog box on click
$('a#show_login').on('click', function(e){
$('body').prepend('<div class="login_overlay"></div>');
$('form#login').fadeIn(500);
$('div.login_overlay, form#login a.close').on('click', function(){
$('div.login_overlay').remove();
$('form#login').hide();
});
e.preventDefault();
});
// Perform AJAX login on form submit
$('form#login').on('submit', function(e){
$('form#login p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#login #username').val(),
'password': $('form#login #password').val(),
'security': $('form#login #security').val() },
success: function(data){
$('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
You would need to use wp function for login.
http://codex.wordpress.org/Function_Reference/wp_signon
Then use ajax to access this function to log in. You could write a log in function in functions.php
Click below to see how to use ajax in wordpress.
http://wpmu.org/how-to-use-ajax-with-php-on-your-wp-site-without-a-plugin/
<form class="well form-inline" id="login">
<div id="message"></div>
<div id="loading" style="display:none;"></div>
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
jQuery(document).ready(function(){
jQuery('#loading').hide();
jQuery("#loginButton").click(function() {
jQuery('#message').hide().html('');
jQuery('#loading').hide();
var input_data = jQuery('#login').serialize();
var logUser = jQuery('#loginUsername').val();
var logPass = jQuery('#loginPassword').val();
if(logUser == '' && logPass != ''){ jQuery('#message').show().html('Your Username is empty!'); return false; }
if(logPass == '' && logUser != ''){ jQuery('#message').show().html('Your Password is empty!'); return false; }
if(logUser == '' && logPass == ''){ jQuery('#message').show().html('Your Username and Password is empty!'); return false; }
jQuery('#loading').show();
jQuery.ajax({
type: "POST",
url: "<?php echo site_url('wp-login.php','login_post'); ?>",
data: input_data,
success: function(msg) {
// login success. redirect users to some page.
jQuery(location).attr('href', '<?php echo home_url( '/thank-you/' ); ?>');
},
error: function(msg) {
// login error.
jQuery('#message').show();
jQuery('#message').html("<?php _e('Your login is not correct. Please try again.'); ?>");
jQuery('#loading').hide();
}
});
return false;
});
});
All AJAX-requests in WordPress must go though wp-admin/admin-ajax.php. wp-login.php won't respond.
http://codex.wordpress.org/Class_Reference/WP_Ajax_Response
There is a set of actions available but none of them comes close to a login-method. You could register your own actions though and handle the login process yourself if you know what you are doing.
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action('wp_ajax_my_login_action','my_action');
add_action('wp_ajax_nopriv_my_login_action','my_action');
function my_action(){
$userdata = array(
'user_login' => $_POST['user_login'],
'user_password' => $_POST['user_password']
);
$user = wp_signon($userdata);
$response = array();
if ( is_wp_error( $user)) {
$response = array('status'=>'fail', 'msg' => $user->get_error_message() );
}
else{
$response = array('status'=>'pass');
}
echo json_encode($response);
die;
}
add_shortcode('login','loginfunction');
function loginfunction()
{
if( is_user_logged_in() ){
echo 'logout';
}
?>
<center>Login Form:</center>
<form action="" method="post" id="login">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control form-control-sm" id="user_login" aria-describedby="emailHelp" name="user_login">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control form-control-sm" id="user_password" aria-describedby="emailHelp" name="user_password">
</div>
<input type="hidden" name="action" value="my_login_action">
<button type="submit" class="btn btn-primary btn-block">log in</button>
<div class="sign-up">
Don't have an account? Create One
</div>
</form>
<script>
var ajax_url= '<?php echo admin_url('admin-ajax.php');?>';
jQuery(document).ready(function($){
$("#login").submit(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url: ajax_url,
data:{
action:'my_login_action',
user_login:$('input[name="user_login"]').val(),
user_password:$('input[name="user_password"]').val()
}
}).done(function(response){
let result = JSON.parse(response);
if(result.status=='pass')
{
window.location.href='http://localhost/check_wp/';
}
else{
// alert(result.msg);
alert('Sorry Password is worrng');
}
})
});
});
</script>
<?php
}
For some reason the newsletter sign-up form bar I'm creating is not working as it should in IE. In fact, it's not working at all. If you visit the link below in Chrome or Firefox it works like it should, but in any version of IE it doesn't.
Anyone have any leads to fix this?
Here's the code, summarized:
$(function() {
$('#name').textboxhint({
hint: 'First Name'
});
$('#email').textboxhint({
hint: 'Email Address'
});
$("#submitButton").click(function() {
// VALIDATE AND PROCESS FORM
var name = $("#name").val();
var email = $("#email").val();
var dataString = 'name='+ name + '&email=' + email;
// HANDLE DATA: SHOW ERROR IF FIELDS ARE BLANK
if (name=='' || name=='First Name' ){
$('.errorIconName').show();
return false;
}
if (email=='' || email=='Email Address'){
$('.errorIconEmail').show();
return false;
}
else {
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(){
$('#signupWidget').fadeOut(400).hide();
$('#thankyouText').fadeIn(700).show();
$('.errorIcon').fadeOut(200).hide();
$('#signupWrap').delay(3000).fadeOut(800);
}
});
}
return false;
});
});
and...
<form action="" method="post">
<span id="sprytextfield1" class="pr20">
<input name="name" id="name" type="text"/>
<div class="errorIconName" style="display:none"></div>
</span>
<span id="sprytextfield2" class="pr20">
<input name="email" id="email" type="text"/>
<div class="errorIconEmail" style="display:none"></div>
</span>
<span>
<input type="submit" name="widgetButton" id="submitButton" value="SUBMIT"/>
</span>
</form>