How to retrieve current user session id from ci_sessions.? - ajax

I want to get current session id to use it in all pages. I want to pass session data in header. I can store my session in ci_sessions table. But how can I retreive current login username/sesson_id from ci_sessions.
here is my ci_sessions code.
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(128) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
here is session setting code
if($this->form_validation->run())
{
$username = $this->input->post('login_username');
$password = $this->input->post('login_password');
// ip address
//$ip_address= $this->user_activity->get_client_ip();
//Retrieving session data and other data
//$captcha_code=$_SESSION['captcha'];
//$user_agent=$_SERVER['HTTP_USER_AGENT'];
//call the model for auth
$this->load->Model('Auth_model');
if($this->Auth_model->login($username, $password)){
$data = array(
'client_username' => $username,
'is_logged_in' => true
);
$this->session->set_userdata($data);
$this->load->view('include/header', $data);
//$this->session->set_flashdata('item', $datav['name']);
}
else{
echo'something went wrong';
}
I am using pop dailog for login and signup so here is my ajax.
<script>
$("input#login_btn").on('click',function(event){
event.preventDefault();
var x = document.forms["loginform"]["login_username"].value;
var x1 = document.forms["loginform"]["login_password"].value;
var y = document.getElementById('login-error');
var z = document.getElementById('password-error');
if (x == "") { y.style.display ='block'; }else{ y.style.display ='none'; }
if (x1 == "") { z.style.display ='block'; }else{ z.style.display ='none'; }
var d = document.forms["loginform"]["login_username"].value;
var d1 = document.forms["loginform"]["login_password"].value;
if(d != '' && d1 != ''){
var url = $(this).attr('action');
var method = $(this).attr('method');
var data = $(this).serialize();
$.ajax({
url:url,
type:method,
data:data
}).done(function(data){
if(data !=='')
{
if(d !== '' && d1 != '' ){
//$("#login_fail").show('fast');
//$("#login_fail").effect( "shake" );
$('#loginform')[0].reset();
//var url = $('#current_loginurl').val();
//window.location.href=url;
var url = $('#current_loginurl').val();
window.location.href=url;
}
}
else
{
var url = $('#current_loginurl').val();
window.location.href=url;
throw new Error('go');
}
});
$( "div" ).each(function( index ) {
var cl = $(this).attr('class');
if(cl =='')
{
$(this).hide();
}
});
}
});
</script>

Find current session from table like below.Get the records order by id in descending order having limit 1.
$this->db->order_by('id', 'DESC');
$this->db->limit(1);
$last_session = $this->db->get('ci_sessions')->row_array();
print_r($last_session['data']);//prints current session data
UPDATE
But the easiest way to get current user session id is make use of session library.Like this..
$this->load->library('session');
$id = $this->session->userdata('id');//id is session variable that you set
echo $id;

Related

Request input null in Laravel Controller

Hi I have a problem with getting the value of input using request in Controller, it's always return null. This is my code in jquery I am using Ajax to pass value to controller.
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance', '')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
And this is my code in controller. I am trying to get the data using request but it returns null when I checked it. What would be the cause? Please help me. Thanks
public function index($id = 0,Request $request)
{
if($id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$id)->get();
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$id)-
>get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances','sUser'));
// dd($start);
}
// return view('manage.index');
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
}
don't forget {{csrf_field }} in form and put id in input name is id
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance.update')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
public function index(Request $request)
{
if(request->id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$request->id)->get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$request->id)->whereBetween('Date',
[$start,$end])-
>get();
return view('manage.index',compact(['attendances'=>$attendances,'sUser'=>$sUser]));
// dd($start);
}
}

Ajax doesn't update properly each time

I wrote different code (at least twice) where Ajax is supposed to change an innerHTML-value by a database call (GET). While the first requests succedes in a 100 % of the time (changing a value in the database) the next commands that extracts the new Information to update the HTML-file fails in about 20-30 % of the time, receiving the wrong response from the xerver (an old value).
I tried tracking the error but can't find it since it only appears sometimes after a call. The following code is just the relevant part of my problem.
<p>I like <b><span id="numCom"><?php echo liked_comments(); ?></span></b> comments.</p>
// Each comment has a likeComment and CountComments function that triggers the Ajax:
let likeIcon = document.getElementsByClassName("like-icon");
for(let i = 0; i < likeIcon.length; i++){
likeIcon[i].addEventListener("click", likeComment);
likeIcon[i].addEventListener("click", countComments);
}
function likeComment(){
let child = this.children[0];
let mainID = this.parentElement.parentElement.id;
url = "ajax/like_comment.php";
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
if(this.status == 200){
let result = this.responseText;
if(result == "t"){
child.classList.remove("red-text");
} else if (result == "f") {
child.classList.add("red-text");
}
}
}
xhr.send("com_id=" + mainID);
}
function countComments(){
let numCom = document.getElementById("numCom");
let xhr = new XMLHttpRequest();
let url = "ajax/count_liked_comments.php";
xhr.open("GET", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function(){
if(this.status == 200){
numCom.innerHTML = this.responseText;
}
}
xhr.onerror = function(){
console.log("Error");
};
xhr.send();
}
// In the php-files these functions are executed:
function like_comment($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
if($l == 0){
// UPDATE TO 1
$query = "UPDATE comments SET liked = 1 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
} else if($l == 1) {
// UPDATE TO 0
$query = "UPDATE comments SET liked = 0 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
}
}
function is_liked($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
return $l;
}
function liked_comments(){
global $db;
$query = "SELECT comment_id FROM comments WHERE liked = 1";
$result = mysqli_query($db, $query);
return mysqli_num_rows($result);
}
The code ist just a demonstration and not really neccessary to understand the problem. In another project. I change the value of a table row via Ajax and afterwards want to update the result. This only happens in about 70 to 80% of the time. All the other times and old value is returned

Making Laravel Cart

I'm collecting data from a form and sending to a controller
$('form').submit(function(e){
e.preventDefault();
var supplier = $('select[name="supplier"]').val();
var reqdate = $('input[name="reqdate"]').val();
var priority = $('input[name="priority"]:checked').val();
if( supplier !='' && reqdate !=''){
var Material_ID = [];
var Material_Name = [];
var Mat_Quantity =[];
var Unit_Price =[];
var Cost =[];
$('.matid').each(function(){
Material_ID.push($(this).text());
});
$('.matname').each(function(){
Material_Name.push($(this).text());
});
$('.unitprice').each(function(){
Unit_Price.push($(this).text());
});
$('.matqty').each(function(){
Mat_Quantity.push($(this).text());
});
$('.matcost').each(function(){
Cost.push($(this).text());
});
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('purchase.sessionstore') }}",
method:"POST",
data:{supplier:supplier,reqdate:reqdate,priority:priority,Material_ID:Material_ID,Material_Name:Material_Name,Unit_Price:Unit_Price,Mat_Quantity:Mat_Quantity,Cost:Cost,_token:_token},
success:function(data){
alert(data);
}
});
}
in the controller, I'm trying to put all variables into a Session
public function storeSessionData(Request $request){
if($request){
$supplier = $request->get('supplier');
$duedate = $request->get('reqdate');
$priority = $request->get('priority');
$token = $request->get('_token');
$materialid = $request->get('Material_ID');
$materialname = $request->get('Material_Name');
$matqty = $request->get('Mat_Quantity');
$unitprice = $request->get('Unit_Price');
$cost = $request->get('Cost');
$cart[] = array($supplier, $duedate,$materialid,$priority,$materialname,$matqty,$unitprice,$cost);
Session::set('cart', $cart);
return $cart;
}
}
I want to open a view with session data to show ordered items (just like a page to confirm cart)
What I want to do - collect data from a dynamic form and display them with a second view, on that view I will save them to database
how can I do it, please explain

Modify request object in Symfony 2

i have the following code on my controller:
/**
*
* #Route("/{discountLevelItemId}/manage-product/update", name="discountlevel_manage_product_update", defaults={"_format"="json"} )
* #Method("POST")
*/
public function manageProductUpdateAction($discountLevelItemId, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:DiscountLevelItem')->find($discountLevelItemId);
$form = $this->createForm(new DiscountLevelItemCollectionType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
//remove items without discount type
foreach ($entity->getDiscountLevelItemProducts() as $item) {
if (!$item->getDiscountType()) {
$entity->getDiscountLevelItemProducts()->removeElement($item);
$em->remove($item);
}
}
$em->persist($entity);
$em->flush();
$responseData = array(
'status' => 'success',
'message' => 'Supplier product discounts successfully saved.'
);
} else {
$responseData = array(
'status' => 'error',
'form' => $this->renderView('CIInventoryBundle:DiscountLevel:manageProducts.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
))
);
}
return new Response(json_encode($responseData), 200, array('Content-Type'=>'application/json'));
}
This action is called via ajax. Before calling this controller i filtered some data out like so:
initForm: function() {
//submit form function
var options = {
delegation: true,
dataType: "json",
beforeSubmit: function(arr, $form, options) {
//holds objects every four looping
var tempArray = new Array();
//holds changed objects that will only be submitted in the server.
var changedArray = new Array();
var found = false;
var idx = 1;
//get the token then remove from arr.
changedArray.push(arr.splice(arr.length-1,1)[0]);
for (var j = arr.length-1; j >= 0; j--) {
var obj = arr[j];
if ( viewCtrl.dliProductsChanged.indexOf(obj.value) != -1 ) {
found = true;
}
tempArray.push(arr[j]);
if(idx % 4 == 0) {
if (found == true) {
for(var i = 0; i < tempArray.length; i++){
changedArray.push(tempArray[i]);
}
found = false;
}
tempArray.length = 0;
}
idx++;
}
arr.length = 0;
for(var i = 0; i < changedArray.length; i++){
arr.push(changedArray[i]);
}
viewCtrl.dliProductsChanged.length = 0;
$form.find( ".submit-button" ).button( "loading" );
$form.find( ".discount-value, .trucking" ).addClass( "uneditable-input" );
$form.find( ".discount-type" ).attr( "readonly", true );
},
success: function(responseText, statusText, xhr, $form) {
if ( responseText.status == "success" ) {
viewCtrl.modal.modal( "hide" );
$.growl.notice({ title: "<strong>Saved</strong>", message: responseText.message, size: "large", duration: 5000, location: "br" });
viewCtrl.dliProductsChanged.length = 0;
} else {
viewCtrl.modal.find( ".modal-content" ).html( responseText.form );
}
$form.find( ".submit-button" ).button( "reset" );
}
};
$( "#manage-products-form" ).ajaxForm( options );
},
My question is, how can i repopulate the form with data i filtered out when the form gets invalid? The first thing came out of my mind is modifying the request object and then rebinding it again but i dont know how to implement that...
Any insights?
PS: I user JQUERY Form Plugin on form submission.
Thanks!

How to get post request using Symfony2

For some reason I can't get the post variables from the controller
The AJAX/Javascript
function uploadImage(userActionPath,type)
{
if( (userActionPath == 'undefined') || (type == 'undefined')) {
console.error("no parameters for function uploadImage defined");
}
if((base64code == 'undefined') || (base64code == null))
{
console.error("please select an image");
}
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
alert(base64code); //<- shows the base64 code, so its there
var params = userActionPath+"?imagebase64="+base64code+"&type="+type;
xml.open("POST",userActionPath,true);
xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
}
The controller
class LiveuploadController extends Controller
{
/**
* #Route("/LiveUpload",name="fileLiveUpload")
* #Template()
*/
public function indexAction(Request $request)
{
//I have tried these but 'imagebase64' returns null
//returns null
$value = $request->request->get('imagebase64');
//returns null
$value = $request->query->get('imagebase64');
//returns null
$value = $this->get('request')->request->get('imagebase64');
$response = array('f'=>0,'base64'=>$value);
return new Response(json_encode($response));
}
}
The request headers also show that the variables are being sent.But both the type AND the imagebase64 variables return null on the controller
The problem is with the way that you have setup the XmlHttpRequest. You have set it up like it should be using GET, but when you want to POST, it is a bit different. Take a look at this question for more info on how to send a POST request. The quick and dirty of it is:
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var params = "imagebase64="+base64code+"&type="+type;
xml.open("POST", userActionPath, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.setRequestHeader("Content-length", params.length);
xml.setRequestHeader("Connection", "close");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
In your example code, you are setting the header to expect JSON, but your params are urlencoded. Setting the proper header should do the trick.
And in your controller, if you are using POST, then you should get the request variables like this:
// Use this for getting variables of POST requests
$value = $request->request->get('imagebase64');
// This is used for getting variables of GET requests
$value = $request->query->get('imagebase64');
This line of code in your JS:
xml.open("POST",userActionPath,true);
You are actually supplying userActionPath instead of params variable. It should be:
xml.open("POST",params,true);
As for the controller's code you should use:
$value = $request->query->get('imagebase64');
Hope this helps...

Resources