I am using two ways for user login in codeigniter:
One is by typing url like this localhost/mySite/login
Other is popup dialog appear when I click a link from localhost/mySite
When I'm following step 2 then calling a function using ajax request.
both time I am calling same function. but when call to the function using Ajax load an additional header.
I used following code for the calling function.
if ($this->input->is_ajax_request()){
echo json_encode(array('status'=>'success','url'=>'auth/enable_account'));
exit();
}
else {
redirect ( "auth/enable_account",'refresh');
}
My jquery code
jQuery('#signin_form').submit(function(event) {
var email = jQuery('#email').val();
var password = jQuery('#password').val();
var remember = jQuery('.dev_signin_remember').is(':checked');
jQuery.ajax({
url:baseurl+'auth/login',
type:'POST',
data:{'email':email,'password':password,'remember':remember},
dataType:'json',
success:function(data){
if(data.status == 'success') {
if(data.url != '') {
window.location.replace(baseurl+data.url);
}
else {
window.location.replace(baseurl+"auth/login");
}
}
else {
jQuery('.dev_signin_error').html('Invalid Username or password');
}
}
});
setTimeout(jQuery.unblockUI);
});
Related
I have a simple ajax code which saves the category and subcategory id in session. These two variables save in session but on next reload both values does not exist in session.
This session issue is only with ajax. I have other points where i am storing and retrieving session and it is working file.
Here is my ajax call.
$("#search-select-category").on("click", function () {
console.log("sending ajax");
$.ajax({
type: "POST",
url: $("#select-category-search").prop('action'),
data: {
"_token": $("#select-category-search").find('input[name=_token]').val(),
"category_id": $("input[name='category-search']").val(),
"subcategory_id": $("input[name='subcategory-search']").val(),
},
success: function (response) {
var response = JSON.parse(response);
console.log(response.message);
if(response.error) {
console.log("error is here");
$(".search-category-error span").text(response.message);
$(".search-category-error").show();
}
else {
console.log("selection is good");
$(".search-category-error").slideDown();
$(".select-category-modal").modal('hide');
}
}
});
});
and the function that executes on ajax call is as follows
public function ajax_select_category_search(Request $request) {
$error = false;
$message = "";
if (empty($request->category_id) || empty($request->subcategory_id)) {
$error = true;
$message = "Category or Sub Category is not selected";
}
if ($error == false) {
session(['category_search' => $request->category_id]);
session(['subcategory_search' => $request->subcategory_id]);
}
$response['error'] = $error;
$response['message'] = $message;
echo json_encode($response);
die();
}
I have tried using file and database session but same problem in both cases. I am using laravel 5.3
Session class is also imported in the class i am using and there are no errors when i use this function.
The reason is i had a die() in the php ajax function. I don't know why remove added session when you have a die() in your ajax call. However i removed the die() and it worked perfectly.
I have jQuery Login Form that the function is to check user validation.
Here is the JS :
$(document).ready(function()
{
$('#button_sign_in').click(function(){
console.log('login');
$.ajax({
url: "login",
type: "post",
data: $('#login_form').serialize(),
success: function (data) {
//console.log('data:'+data);
if (data.user) {
$('#lblUsername').text(data.user.username);
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
},
error: function (e) {
console.log('error:'+e);
}
});
});
});
The logic is, if wrong username or password then the button will shake. If correct login then redirect to the home page.
and here is my PHP function :
require ("functions/_db_.php");
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT username, password FROM t_users WHERE username='$username' && password='$password'");
$found = mysql_num_rows($query);
if ($found > 0)
{
header('location:home.php');
}
Now the problem is : if login corrected, the page won't redirect to home page.
Any suggestions ?
Maybe because you're not doing the redirect itself?
success: function (data) {
//console.log('data:'+data);
if (data.user) {
$('#lblUsername').text(data.user.username);
window.location = '/home.php'; // redirect to the homepage
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
}
PHP redirect using header won't work if you send it to the client via AJAX. You have to redirect it on the client-side using JS in this case.
Keep your PHP Script as bellow
//Check your inputs against to mysql injections
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT username, password FROM t_users WHERE username='$username' && password='$password'");
$found = mysql_num_rows($query);
if ($found > 0)
{
$res='SUCCESS';
}
else
{
$res='ERROR';
}
$ary=array("status"=>$res);
echo json_encode($ary); //Json output - we are sending the assynchronus data in json format
and Your Script
$.ajax
({
url: "login",
type: "post",
data: $('#login_form').serialize(),
dataType:'json', //We need ajax data in json type
success: function (data)
{
if (data.status=='SUCCESS') //status is proper of the json object, which we gave in php code in above script
{
window.location='home.php';
}
else
{
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
},
error: function (e) {
console.log('error:'+e);
}
});
if (data.user)
{
$('#lblUsername').text(data.user.username);
window.location = "home.php";
}
Dude, i think you have the problem at PHP side, not the javascript.
Considering this, here is your solution , not location it is Location
header('Location: http://www.example.com/');
Document
When you do AJAX call to a php script, calling header() will not load a new page in the browser. You can respond to AJAX call by echo 'success/fail' and redirect to the desired page yourself by checking the response in the success: part of AJAX. And don forget to set the php session, and check whether the user login made successful or not in the page which you want to display after login. So your code in php will be,
if ($found > 0) {
//set session here
echo 'success';
}
else
echo 'fail';
and in Ajax,
success: function (data) {
if (data == 'success') {
window.location = "home_page.php";
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
}
in you hompage php,
check for the session.
I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});
I have the following method which allows a user to login into my application:
public function login()
{
if($this->Auth->user())
{
$this->Session->setFlash(__('Already logged in...'), 'default', array(), 'auth');
$this->redirect(array('controller'=>'pages','action'=>'display','home'));
}
if ($this->request->is('ajax'))
{
$this->layout = 'ajax';
if ($this->Auth->login())
{
}
else
{
}
}
else if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
It allows a user to login either using a post request or via an ajax request. However with regards to the ajax requests how do I pass the results back using JSON? So for example if the user enters the wrong details pass back an error message?
I have the jQuery AJAX already setup so I just need to do some extra logic in the success method to deal with the return which will either show the error message from the server or do a redirect again based on the return from the server.
e.g.
$('form').live('submit', function (event) {
// Declare the form
var form = $(this);
// Stop the form from doing a native postback
event.preventDefault();
// Get the data from the form
var data = form.serialize();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (responseHtml) {
// If correct login details
if(success){
window.location.href('INSERT LOCATION TO REDIRECT TO FROM SERVER');
} else {
alert('INSERT MESSAGE FROM THE SERVER');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error!');
}
});
});
Can anyone help? I'm using CakePHP 2.0 and all of the tutorials I have seen on the net and on here have either been outdated or much too long-winded for what I'm trying to achieve.
Edit: you need to use the following php code
if ($this->Auth->login())
{
$arr = array("login" => "true" , "redirect" => "/redirect_url");
echo json_encode($arr);
}
else
{
$arr = array("login" => "false" , "error" => "Invalid Login Credentials");
echo json_encode($arr);
}
on the javascript side you need to modify your javascript to handle json values using jQuery.getJSON. example of jQuery.getJSON is availabe here http://api.jquery.com/jQuery.getJSON/
use this jQuery code
<script type="text/javascript">
$.getJSON("login.php", function(data) {
if(data.login)
{
//redirect user with data.redirect
}
else
{
//display error with data.error
}
})
</script>
On my website I am using ajax post request to show content around my site, this is done using this code,
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
var data = "calltype=full&url="+url;
$.ajax({
url:url,
type: "POST",
data: data,
success : function (html) {
$('#left-content-holder').html(html);
}
})
});
as you can see I am passing the url into the `$_POST' and I can access this in the method the javascript calls, this method is called get_content_abstract and looks like this,
public function get_content_abstract() {
$this->load->model('content_model');
if($this->input->post('calltype') == "abstract"){
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
elseif($this->input->post('calltype') == "full") {
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['full'] = $query;
}
$this->load->view('template/full-content', $data);
}
}
How ever I have no added a new function that will allow the user to save the content to 'bookmarking system', however in my method I cannot access the post using codeigniters $this->input-post('url') (where URL is the one of peices of data passed in the javascript), it says that the post is empty when I var dump it, this is done using this method,
public function love_this() {
die(var_dump($this->post->input('url')));
}
can anyone help as to why the post is empty in this love_this method?
Shouldn't:
public function love_this() {
die(var_dump($this->post->input('url')));
}
Actually be
public function love_this() {
die(var_dump($this->input->post('url')));
}
See:
http://codeigniter.com/user_guide/libraries/input.html