I have a Login/logout method located in my home controller. There are username and password textboxes on all the pages which are generated by different controllers.
I've a common jquery file for all my views which uses ajax to post the username and password from any of the pages to the Home controller Login/Logout method. But this does not seem to work as those pages are being generated by different controllers and not the Home controller. When I check firebug I see the url mentioned in the Ajax script is being appended to the controller of that page and no actual redirection takes place.
I've seen that it is usually recommended to use a self made helper in such scenarios. But I'm not sure how can that be used via jquery ajax.
Home controller
function validate_login_user()
{
$this->load->model('model');
if ($this->sristi_model->validate_login())
{
$data = array (
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
$this->load->view('includes/logged_in.php');
//return true;
}else{
$this->load->view('includes/loginerror.php');
//return true;
}
}
The javascript
$('#sitelogin').on('click', '.login', function(){
var username = $('#username').val();
var password = $('#password').val();
if (username == "" || password == ""){
$('#error').fadeIn(200).delay(1000).fadeOut(1000);
return false;
}else if(username !== undefined && password !== undefined)
{
$.ajax({
url:"home/validate_login_user",
type:'POST',
data:{username:username,password:password},
cache:false,
success:function(msg){
$('#sitelogin').html(msg).hide().fadeIn(800);
$('#loginerror').delay(2000).fadeOut(1000);
}
});
return false;
}else{
return false;
}
});
When I try to login through the Product controller I get this in Firebug
URL: POST validate_login_user
localhost/ci/product/categories/localhost/ci/home/validate_login_user
Status: 500 Internal Server Error
Domain: localhost
Size: 1.6 KB
Remote IP: [::1]:80
Let me know if you find something...
I was somehow able to see this answer in my notifications but I don't see it on this page. Preceding the ajax url with a slash did the job and now everything is working fine.
Thanks to whoever commented that.
Related
I use my own Framework, in localhost all works perfectly fine but not on the server.
I'm logged, so I've a session id.
On a ajax request, the php script doesn't keep my session, if I return the session, the session are empty but me in my side, I keep the session.
It's like if the server thinks the ajax request is a new user.
I don't know where to look and I can't post all the framework code here...
Yesterday I already have this issue (at work) then at home, I retested and all worked great...
I don't get it...
$(document).on('click', '.edit', function(){
$.ajax({
type: "POST",
url: ROOT+"list",
data: {id:id},
headers: {
Accept : "application/json; charset=utf-8"
},
cache: false,
success: function(data){
console.log(data.sess.ROLE);
if(data.status == "error"){
//error
}else{
//ok
}
}
});
});
Controller:
public function editAction(){
//if(!$this->ROLE('tokayn')){ $this->redirectUrl('thread_index'); }
if(Request::POST()){
if(is_int($_POST['id'])){
$user = $this->batiments->findById($_POST['id']);
if($user->id_proprio == $_SESSION['id']){
$data = array('status'=>'ok', 'message'=>$user);
Request::renderJson($data);
}else{
Request::renderJson(array('sess'=>$_SESSION));
//$data = array('status'=>'error', 'message'=>'error');
//Request::renderJson($data);
}
}else{
$data = array('status'=>'error', 'message'=>'error');
Request::renderJson($data);
}
}else{
//$this->redirectUrl('thread_index');
}
}
If a user is not logged, the session role is 'visitor' but if he's logged, the session role is 'connected'.
I've a echo before the ajax form and it's 'connected'.
Then, on submit the ajax form, the ajax request return 'visitor' but if I refresh, I keep the 'connected' echo...
I've faced this issue for me the problem was I was using
https://server:1234/somecontroller
while i was requesting from ajax as
http://server:3344/somecontroller
and session was not shared between https and http so double check if this apply for you.
I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.
$(function () {
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password },
function (result) {
alert('finished post');
//if the result is not 1
if (result == 0) {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
});
});
});
Here is the php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['username'];
$mypassword= $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();
$admin = $sql['admin'];
$password_hash = $sql['UserPass'];
$salt = $sql['salt'];
/*** close the database connection ***/
$dbh = null;
if(crypt($mypassword, $salt) == $password_hash){
// Register $myusername, $mypassword and redirect to file
$_SESSION['myusername'] = $myusername;
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 1;
if($admin == 1){
$_SESSION['admin'] = 1;
}
header("location:search.php");
}
else {
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 0;
echo 0;
}
Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:
$(function () {
$("#login_form").on('submit', function(){
console.log('form submitted');
// get the username and password
var login_info = { username: $('#username').val(), password: $('#password').val() }
// use ajax to run the check
$.ajax({
url: '../php/checklogin.php',
type: 'POST',
data: login_info,
success: loginHandler
error: function(xhr, status, err){ console.log(xhr, status, err); }
});
return false;
});
function loginHandler(loggedIn){
if (!loggedIn) {
console.log('login incorrect');
} else {
console.log('logged in');
}
}
});
...ok great, we're looking a little better now. Let's go over the changes made quickly.
First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.
Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.
Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.
We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.
Finally we're returning false so that the page doesn't refresh.
Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.
I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.
Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )
Hope this helps!
Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this
$("#login_form").submit(function (e) {
e.preventDefault();
// and so on
See http://api.jquery.com/event.preventDefault/
you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.
$("#login_form").submit(function (e) {
e.preventDefault();
Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this
checklogin.php?username=x&password=y
try this:
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password }, function (result) {
alert('finished post');
//if the result is not 1
if (result == '0') {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
}, 'text');
});
}, 'text');
maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.
I have a registration form for my website that requires a user to fill in ~6 fields, with their email as their username on the system. When a user registers, I want to first check if they are not already a registered user in our system, and if they are, redirect them to the login page. If they are not registered, registration should proceed to the registration page.
I've been trying to do this with the following ajax code, but it doesn't work - if the user is already registered, it still proceeds to the registration page:
function Chkreg()
{
var uemail = document.registration.email;
var not_reg;
$.ajax({
async: false,
type: "POST",
url: "chkreg.php",
data : "email="+uemail.value,
dataType: "json",
success: function (data) {
var success = data['success'];
if(success == false){
var error = data['message'];
alert(error);
window.location.href="login.php";
not_reg = false;
return false;
}
if(success == true) {
not_reg = true;
return true;
}
}
});//end ajax
return not_reg:;
}//end function
The form itself is defined as follows:
`<form name='registration' method="POST" action="registration/register.php" onsubmit="return Chkreg();">`
so, a false return from the Chkreg function should not post to register.php, but Chkreg() seems to always return true.
Any ideas how to fix it, or an alternate way to do this?
Because you're doing the ajax call with async:false, you don't need the return true or return false inside of it. That could be where things are going wrong, since you are returning from the anonymous function in the ajax call, not Chkreg(). Just returning not_reg outside of the ajax call will work.
That said, I would declare not_reg = false when you initialize the var. That way it's false until proven true. Or vice-y-versa -- I can't tell because of the negation in the variable name.
Also, inside of your (success == false) if-block, you are executing
window.location.href = "login.php";
which immediately redirects the user to login.php. You may want to alter the flow entirely and change the inline js for the form's onsubmit event
onsubmit="Chkreg(); return false;"
Then, inside Chkreg(), you could submit the form with javascript if they are not a registered user already.
Also, === and !== are preferred over == and != (especially when establishing if a variable is true or false, in case your values can be interpreted as truthy).
Lastly, Developer Tools are your friend (or Firebug). What response is the server giving when chkreg.php is being requested?
Check what the actual response is with firebug (or whatever your browsers dev kit)....I would be what you want is
if (success == "false") {
I'm working on a HTML5 mobile app. The app only uses 1 html file which contains a login form. On submit javascript posts the username and password to a php script on the server which returns 'true' or 'false'.
When the authentication returns true the app changes the html5 page and stores the username and password in html5 local storage.
Since this is sensitive data my question is how to store these values in a secure way?
function handleLogin() {
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
if(u != '' && p!= '') {
$.post("http://www.mywebsite.com/login.php", {username:u,password:p}, function(res) {
if(res == true) {
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
$.mobile.changePage("index-2.html");
} else {
/// error message
}
$("#submitButton").removeAttr("disabled");
},"json");
}
return false; }
I would suggest using Access tokens, since this can be updated and changed frequetly, it also doesnt reveal who the user or what their hashed password is.
http://php.net/manual/en/oauth.getaccesstoken.php
Edit: You do NOT want to use localStorage!
I have a problem in server side retrieving session with using ajax post request. Here is my sample code:
JavaScript:
$(function() {
$('.jid_hidden_data').submit(function() {
var serialized = $(this).serialize();
var sUrl = "http://localhost/stuff";
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
success: function(data) {
alert(data);
}
})
return false;
});
});
CodeIngiter(PHP) side:
function stuff()
{
$post_stuff = $this->input->post('my_stuff'); // WORKS PERFECTLY
$user_id = $this->session->userdata('user_id'); // RETURNS NULL
}
Where commented returns NULL it should return users session data, because it really exists. What is the problem? Method post doesn't get cookies or what? Thanks for any help!
Update:
For clarification i have session set with $this->session->set_userdata($data).
And I don't have a problem when posting it without js/ajax. I mean with plain form submit it works fine.
I had a similar problem when accessing a CI app using different domain names. Even though those domain names pointed to the same web server, I got two separate sessions.
For example, consider this Controller :
class User extends Controller
{
function User()
{
parent::Controller();
$this->load->library('session');
}
function login()
{
$this->session->set_userdata('login_token', true);
echo 'finished logging in';
}
function logout()
{
$this->session->unset_userdata('login_token');
echo 'finished logging out';
}
function status()
{
if ($this->session->userdata('login_token'))
{
echo 'logged in';
}
else
{
echo 'not logged in';
}
}
}
I access the following URLs in sequence. Beside each URL is the corresponding output :
http://localhost/app/user/login "finished logging in"
http://localhost/app/user/status "logged in"
http://127.0.0.1/app/user/status "not logged in"
So the session I have when accessing the app on localhost does not carry over to 127.0.0.1, even though I'm hitting the same web server.
Could it be that the domain name of the URL in your AJAX script is different to that of the URL that you are testing with?