Codeigniter + ajax(jQuery) session problem - php

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?

Related

Ajax is not working in server but works fine in local host

Ajax call is not working in entire site. But works fine in localhost. I cannot able to debug this issues.
I have used ajax entire website. I totally fed up.
Anyone please help me to fix this bug!!
One of my Sample Ajax Code:
function advanced_addTopic(cid) {
$.ajax({
url: "assets/php/checkSubtopicStatus.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {'cid':cid}, // Data sent to server, a set of key/value pairs (i.e. form fields
success: function(data) // A function to be called if request succeeds
{
if(data==="True"){
$("#subtopicDiv").html($("#subtopicDiv"+cid).html());
$("#advanced_testid").val(cid);
var hiddenCourse=$("#createTest").attr('class');
$("#courseHidden").val(hiddenCourse);
$("#advanced_addquestionModal").modal('show');
$("#subtopic").focus();
$("#question").focus();
var tempVal=$("#getID").text();
$("#advanced_courseHidden").val(cid);
} else {
alert("Create subtopics to insert questions!");
}
}
});
My PHP Code is here:
<?php
class loginValidation {
function validate()
{
ob_start();
session_start();
include "../../connection.php";
$id=$_POST['cid'];
$query = mysql_query("select * from advanced_subtopic where testid='$id'");
if(mysql_num_rows($query)>0) {
echo "True";
}
else {
echo "False";
}
}
}
$loginValidation=new loginValidation;
$loginValidation->validate();?>
My Concosole Log
CONSOLE RESPONSE
Instead of
(data==="True")
we should code like
($.trim(data)=="True")
Should trim the data to avoid unwanted space.
Problem solved.

Ajax reset session php

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.

Use The Language Key In controller of codeigniter

I have an application build in Codeigniter framework.which have functionality of multi language.It works fine In view to convert the each line.But for alert messages which is set from controller i try to use the language key but failed to show the message on view in multi language.
Here is the code of controller from the message has been set to show on view:-
the function of controller to set the message:
function serial_coupon()
{
$admin_session_data= $this->session->userdata('user_logged_in');
$key=$this->input->post('serial');
$res=explode("000",$key);
$key=$res[1];
$result['coupon']=$this->provider_model->get_coupon($key);
if(empty($result['coupon']))
{
$msg=$this->lang->line('language_srch_msg');
$this -> session -> set_flashdata('message',$msg);//if no search found than set the message.
redirect('/provider/');//provider is controller
}
else
{
$this->load->view('header',$admin_session_data);
$this->load->view('show_coupon',$result);
$this->load->view('footer',$admin_session_data);
}
}
Hence it comes to the Provider controller's Index Function to send the message on view:-
function index()
{
$msg=$this->session->flashdata('message');//get the message
$result['msg']=$msg;and set to the array to send in view
$result['rows']=$this->session->userdata('provider_detail');
$user_id=$result['rows'][0]['id'];
$result['coupons']=$this->provider_model->show_coupons($user_id);
$this->load->view('header');
$this->load->view('provider_interface',$result);
$this->load->view('footer');
}
So the message should be display in view:
<p><?php echo $msg; ?></p>
And the other lines where i am using language key Like:
for name:
<?php echo $this->lang->line('language_name');?>
Now please Let me know how can i use the above language key for message in controller??
Thanks In advance and still any doubt feel free to Ask.
Short description :
the problem is not to show the falshdata message.i want the message should be in a particular language in which the user selected.my application in multi language in which the user can select the language from drop down box.and the whole content in convert in to the selected language .but the alert messages comes from controller so how can i convert them in selected language?
I changed my code in function search_coupon but it works for only English language not for Portuguese.Here is my constructor code of provider controller:
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('provider_model');
$lng=$this->session->userdata('about_language');
if($lng=='' )
{
$this->load->language('language','english');
}
else
{
$this->load->language('language',$lng);
}
if($this->session->userdata('provider')=="")
{
redirect('/login/', 'refresh');
}
}
Code for select The language using ajax:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#port').click(function(){
var dummy = 2;
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/session/sessions",
data: "&ID="+dummy+ "&lang="+'portuguese',
success: function(response)
{
if (response == false)
{
location.reload();
}
}
});
});
jQuery('#eng').click(function(){
var dummy = 1;
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/session/sessions",
data: "&ID="+dummy+ "&lang="+'english',
success: function(response)
{
if (response == false)
{
location.reload();
}
}
});
});
});
</script>
And here is the session controller :
function sessions(){
$value= $this->input->post('ID');
$lang= $this->input->post('lang');
$lang=$this->session->set_userdata('about_language',$lang);
return $lang;
}
One solution, perhaps not the best, is to store in the flash var the message key instead of the message. At this moment you are storing:
$this -> session -> set_flashdata('message','No Search Found Of This Serial Number');//if no search found than set the message.
and then you are loading the message:
$msg=$this->session->flashdata('message');//get the message
$result['msg']=$msg;
And showed in the view:
<p><?php echo $msg; ?></p>
I proposed you this solution:
$this -> session -> set_flashdata('message','message_key');//if no search found than set the message.
$msg_key = $this->session->flashdata('message');//get the message key
$result['msg_key'] = $msg_key;
And in the view:
<p><?php echo $this->lang->line('msg_key'); ?></p>
Ok, then do like this: Every time you change your language, set it into session. Load your language file according to your language session value. Then you will have all your messages into your changed language.
$this->lang->load('filename', $this->session->userdata('user_lang'));

PHP Session ID Variable Returned With AJAX

I'm working on an AJAX login system and am not sure how to return the PHP session variable from AJAX unto the login page. My question is, how do I return the php variable unto the login page, if that is even possible. Below is the sample I created.
Login Page
<?php
session_start();
?>
<form>
<input type="text" id="username" />
<input type="text" id="password"/>
<input type="button" id="submit" />
</form>
<script type="text/javascript" >
$('#submit').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.post('ajax_file.php',
{
username: username,
password:password,
},
function (data) {
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"', 2000);
});});
</script>
Here is the ajax page. I understand that the logic doesn't make sense for the session variable to pop out of nowhere, let's just assume that is was created earlier in the page.
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
return $session_user_id = $_SESSION['user_id'];
}
You can just do the AJAX post, set the session variable to the session in the page receiving the post, and it will be stored in the session (it's the same session). In the AJAX callback forward the user to the home page.
Of course you must consider the scenario that the login credentials are incorrect.
The trick is that your JavaScript doesn't even have to know about sessions at all; you can configure PHP to use HttpOnly cookies for its session management via the respective ini setting.
I would implement the AJAX script like this:
session_start(); // start the session
if (login($username, $password)) {
// alter session to hold user id
$_SESSION'user_id'] = $user_id_from_database_or_something;
return true;
} else {
return false;
}
The AJAX complete handler looks at the return value and redirect to the homepage if it was true. Something like below (I'm assuming that the PHP return is translated into something like echo json_encode($return_value):
if (data) {
// do redirect
} else {
// login failed
}
Then, when the user comes to the homepage their browser would send a session cookie so you can determine if they're logged in.
Improving the Answer
FOr Jquery, USe function below
function sendAjax(showAllExist, controller)
{
$.ajax({
type: "post",
url: login.php,
data: yourformdatacomeshere,
beforeSend: function() {
//do whatever you want to do before request
},
error: function() {
//display in case of error
},
success: function(data) {
//display in case of error
if(data!=""){
//redirect use to home pahe
window.location.href ='homepage.php';
}else{
//display login is not correct
}
},
complete: function() {
//hide any event which you have started on beforeSend
}
});
return true;
}
Cant you just do this:
$.post('ajax_file.php',
{
username: username,
password:password,
loginSession: <?php echo $_SESSION['user_id']; ?>
},
function (data) {
//Check here if login is correct.
if correct, create this variable:
var logged= "?logged="+data.SessionID;
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"+logged+"'", 2000);
});})
When data comes back go the homepage.php with a sessionID.
on the php script do this:
if(isset($_GET['logged'])){
start_session();
$_Session['LOGGED']='true';
}
use this method which is improvised above shail answer.
your ajax file code
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
$session_user_id = $_SESSION['user_id'];// this is from your code
$responseArray = array("message"=>"success","sessionId"=>$session_user_id);
}
else
{
$session_user_id = "";
$responseArray = array("message"=>"error","sessionId"=>$session_user_id);
}
echo json_encode ( $responseArray );
die ();
then in ajax function make below changes.
var frmdata = jQuery("#logindata").serialize(); // which contains the data of username and password
jQuery.ajax({
type : "POST"
,url :'ajax_file.php'
,data :frmdata
,dataType: "json"
,success : function(data){
if(data.message == "success")
{
//redirect it to your desire page
}
else
{
//redirect it to your login page
}
}
,beforeSend: function(html){
// some loader goes here while ajax is processing.
}
});
hope this help feel free to ask anything for this answer.

returning php session to ajax

I am having trouble getting jQuery ajax to recognise a session. I am creating a php session from a login script, but what is happening is that when ajax loads the authenticated page, the session is always unset. For example, in the secure page, if I refresh the page, the session id changes each time. I have session_start(); in each page. Can someone please show me the correct way to handle sessions with ajax and php? I have spent 2 days and have used google so much, I will probably get an invite to there xmas lunch :-) I have included the relevant code and would be grateful for any help. Thanks
PS. If it makes any difference, I am trying to develop mobile app using jquery mobile.
login html js
$(function() {
$("#kt_login1").click(function() {
var user = $('#user').val();
var pass = $('#pass').val();
if (user == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=user]').addClass("label")
return false;
}
else if (pass == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=pass]').addClass("label")
return false;
}
else $('label[for=user]').removeClass("label");
$('label[for=pass]').removeClass("label");
//alert(user + pass + ok);
data = 'user=' + user + '&pass=' + pass;
$.ajax({
type: "POST",
url: "testajax.php",
cache: false,
data: data,
success: function(data) {
if (data == 'authenticated') {
//alert(user);
document.location = 'secure.php';
}
else $('#login_message').html('You are not authorised');
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
},
error: function(xhr, ajaxOptions, thrownError) {
jAlert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
testajax.php
<?php
// test wether the user session is already set
$username = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string(md5($_POST['pass']));
mysql_connect('localhost', 'root', '');
mysql_select_db('sample');
//now validating the username and password
$sql="SELECT * FROM user_usr WHERE username_usr='$username' and password_usr='$pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0) {
session_start();
$_SESSION['u_name']=$row['name_usr'];
/*
echo '<pre>';
print_r( $_SESSION['u_name'] );
print_r( $_REQUEST );
echo '</pre>';
exit;
*/
echo 'authenticated';
}
else
{
echo 'Unknown User';
}
?>
+++++SOLUTION+++++
Changed form input from submit to button and voila. All ok
you have to call session_start() each time working with a session (not only when creating it)
see: http://php.net/manual/en/function.session-start.php
There are a whole load of reasons this might be the case - but you're code is upside down! This may well be the cause (or a contributory factor).
You should not treat the existence of a session as evidence of authentication (the contents of the session is another thing altogether). Call session_start() at the top of your script - not conditionally, half-way through.
As to why your session data is not available...that's an FAQ here - have a look at some of the previous answers for potential causes / how to investigate.

Categories