Redirect to home page after successful login using AJAX
It looks like the problem is that you are trying to use the name of the php variable in your javascript to access the php response.
success:function(data){
if($session == true){
window.location.href="http://www.example.com";
}
$("#result").html(data);
}
The variable $session
isn't defined within the scope of the success
function, thus if($session == true)
will always return false, since $session
will be undefined
.
What ever your PHP code echos will be passed into the success
function using the data
param. Since your PHP code is just echoing either a 0 or 1 you would want to update the if
line to if(data == 1)
, or possibly even just if (data)
since if the data variable is just 0 the it should return false, and if it's 1 then it should return true.
Ajax not redirecting after a successful response from php
You have to trim your response....sometimes the string recieved from the server contains whitespace.....and that causes the problem to not redirect to other page.
$.ajax({
url: 'actionlog.php',
method: 'POST',
data: $('#login-form').serialize() + '&action=login',
success: function(response) {
if ($.trim(response) === 'true') {
window.location = '../';
} else {
$('#logAlert').html(response);
}
}
});
How to redirect user on successful ajax call? Otherwise display error message in form
I've rewritten the code for you as it likes like you had quite a few problems.
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: { email: $('#email').val(), loginsubmit: 'yes' },
success:function(response){
if(response == "redirect"){
window.location.replace("http://www.gathercat.com/login/private.php");
}
else{
$("#formResponse").html(response).fadeIn('100');
$('#email').val('');
}
}
})
});
});
This is untested but please let me know if you have any questions about how it works.
Redirect to login page if AJAX url redirects to login page
This is common problem as AJAX request will append the response to the place you want to show . You need to handle it by yourself. Here is my solution , in the case of Session expire and request is AJAX i return the status code 401 and then this is how i handle it at global level. I have put this code in the master page/template.
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status === 401) {
alert('Session is expired. Login again');
window.location.href = '../Admin/Signout.php';
}
});
In codeigniter How to redirect after login using ajax
You need to change few lines of codes in jQuery and Controller function. Here I am attaching updated version of your code. Please refer below:
View (Bootstrap Modal)
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
This is your view file. It will remain same. On clicking on button you have written a script which need to be modified. Will attact after attaching controller's function:
Controller
function index() {
if (!$this->input->is_ajax_request()) {
echo 'No direct script is allowed';
die;
}
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
$result['status'] = 'error';
$result['message'] = validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
$result['status'] = 'success';
$result['message'] = 'Yeah! You have successfully logged in.';
$result['redirect_url'] = base_url();
}else {
$result['status'] = 'error';
$result['message'] = 'Whoops! Incorrect Email & Password. Please try again';
}
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($result));
$string = $this->output->get_output();
echo $string;
exit();
}
Script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(resp) {
if (resp.status == "success")
window.location.href = resp.redirect_url;
else
$('#error-msg').html('<div class="alert alert-danger">' + resp.message + '</div>');
}
});
return false;
});
This is the correct answer. Let me know if you face any issue.
How to redirect to new page using ajax
Right now you are passing the whole page as json data yoou need to relocate to the page like
success:function(data){
if(data==true)
{
window.location.href ="/YourPag.html";
}
);
}
,
Related Topics
Ngoninit Not Being Called When Injectable Class Is Instantiated
How to Block +,-,E in Input Type Number
Force Facebook to Open Link in External Browser for Smart Phones
Syntaxerror: Unexpected Token O in Json At Position 1
Json to CSV Flattening Nested Json
How to Detect iPad and iPad Os Version in iOS 13 and Up
How to Create a Dynamic Jquery Data Table With Json Data and Ajax
Disable Pdf Download and Save Option
Uploading a File from a Bootstrap Modal Using Ajax
Uncaught Typeerror: (Intermediate Value)(...) Is Not a Function
How to Disable Eslint Rule Max Line Length for Paragraph in <Template> of Vue.Js
Npm Warn Enoent Enoent: No Such File or Directory, Open 'C:\Users\Nuwanst\Package.Json'
How to Select Every 2Nd Element of an Array in a for Loop
How to Count Unique Value from Object of Array in JavaScript
Launch Chrome Browser from Internet Explorer
Pass Node Js Variable to Ejs Template