Cannot change php session variable by javascript code [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
MY php code is below:
public function checkWhetherASalaryProcessIsOngoing(){
if(isset($this->session->userdata['salary_is_on_going'])){
echo $this->session->userdata['salary_is_on_going']; }else{echo 'NOTSET';}
}
public function set_salary_is_on_going(){
if(!isset($this->session->userdata['salary_is_on_going'])){$isset = $this->session->set_userdata('salary_is_on_going','SET');}
echo $this->session->userdata['salary_is_on_going'];
}
public function delete_set_salary_is_on_going(){
$this->session->set_userdata('salary_is_on_going','NOTSET');
echo $this->session->userdata['salary_is_on_going'];
}
My javascript code:
$(document).on('click','a#process',function(){
// set the start time
t0 = performance.now();
alert('<?php if(isset($this->session->userdata['salary_is_on_going'])){echo $this->session->userdata['salary_is_on_going'];}?>');
var payment_period_id = parseInt($('#paymentPeriodId').val());
var unit_id = parseInt($('#unitIdz').val());
var user_id = parseInt($('#userIdz').val());
// check whether same session variables exists in all opened pages. function in D:\xampp\htdocs\diganta\assets\js\common_js.php
checkSessionDataWithPageSessionData(function(dataii){
if(dataii === 'NOTCHANGED'){
checkWhetherASalaryProcessIsOngoing(function(dataoo){
if(dataoo === 'NOTSET'){
// if not set then set session variable named salary_is_on_going
set_salary_is_on_going(function(data55){
if(data55 === 'SET'){
progress();
var checkedRows = [];
$("#supervisorList tr").each(function () {
if ($(this).find("input").is(":checked")) {
checkedRows.push({"supervisor_id" : $(this).find("td:eq(1)").text()});
}
});
if(checkedRows.length < 1){
delete_set_salary_is_on_going();
custom_alert('Supervisor not selected.',"Error",10,'right',50);
}
if(checkedRows.length > 0){
ensureItIsNotARevisedSalary(checkedRows,user_id,unit_id,payment_period_id);
}else{return;}
}else{custom_alert('Can not set salary ongoing session variable.',"Error",10,'right',50);return;}
});
}else{custom_alert('A salary process is ongoing.',"Error",10,'right',50);return;}
});
}else{custom_alert('session data change detected. Cannot Execute.<br><br> refresh.',"Error",10,'right',50);return;}
});
});
function ensureItIsNotARevisedSalary(checkedRows,user_id,unit_id,payment_period_id){
var url = '<?php echo base_url();?>primary_salary_processing/ensureItIsNotARevisedSalary';
$.post(url,{payment_period_id:payment_period_id}).done(function(data){
data = parseInt(data);
if(data > 0){
setTimeout(function(data){delete_set_salary_is_on_going();},1000);
custom_alert('This is a revised salary it can not be processed from here.',"Error",120,'right',50);
}
else{checkWhetherSalaryIsLocked(checkedRows,user_id,unit_id,payment_period_id);}
});
}
function checkWhetherASalaryProcessIsOngoing(result){
var url = '<?php echo base_url();?>primary_salary_processing/checkWhetherASalaryProcessIsOngoing';
$.ajax({
url:url,
data:{},
type:"POST",
success:function(data){
result(data);
},
});
}
function set_salary_is_on_going(result){
var url = '<?php echo base_url();?>primary_salary_processing/set_salary_is_on_going';
$.ajax({
url:url,
data:{},
type:"POST",
success:function(data){
result(data);
},
});
}
function delete_set_salary_is_on_going(){
var url = '<?php echo base_url();?>primary_salary_processing/delete_set_salary_is_on_going';
$.ajax({
url:url,
data:{'url2':'<?php echo $this->session->userdata['url'];?>'},
type:"POST",
success:function(data){
},
});
}
After clicking a#process the salary process starts.
The problem is javascript function delete_set_salary_is_on_going() cannot change
session variable having index of 'salary_is_on_going' to 'NOTSET'

Did you forget to write session_start() in your receiving/processing url?
<?php session_start() ?>

Related

Call Controller function from jQuery

I'm working on some codes. Here's my code
jQuery
duration = 30;
var countdown = setInterval(timer,1000);
var url = window.location.origin + '/pro/index.php/Test';
function timer(){
duration = duration - 1;
if(duration<=0){
clearInterval(countdown);
window.location(url+'/next');
}
}
I want to redirect and run function in Test/next. In next() method, it will rule where the link should go. url helper also has been added automatically in Loader
Controller
public $num;
public $val;
public function index(){
// get the value from GET method
$this->num = $this->input->get('num');
$this->val = $this->input->get('val');
}
public function next(){
$x = $this->num;
$x = $x + 1;
if($x < 4){
redirect(site_url('index.php/Test?x='.$x/.'&num='.$this->num));
}
else{
// it will redirect to another page
// redirect(site_url('index.php/Home'));
echo 'x = '.$x.', num = '.$this->num;
}
(The codes above have been simplified).
The method has been run, but the url was localhost/pro/index.php/Test/next and echo-ing :
x = , num =
It seems like the global property doesn't work for the function called from JS/jQuery. Any explanation or solution for this?
You need ajax calling.
In your View file
<button class="call_ajax" name="submit">Call Ajax</button>
<script type="text/javascript">
$('.call_ajax').click(function(){
var value1 = 'some data';
var value2 = 'some data';
$.ajax({
url: '<?php echo site_url('your_controller/your_function'); ?>',
type: 'POST',
data: {
key1: value1,
key2: value2
},
dataType: 'json',
success: function(url) {
window.location.href = url;
}
});
});</script>
in your Controller
your_function(){
$data1 = $this->input->post('key1');
$data2 = $this->input->post('key2');
// do Data Processing
// For return some data ;
echo "https://some-webiste-url/";
// FOR Array
echo json_encode($any_data_array);
}
NOTE : controller Function called from ajax will not do redirection . If you want to direct to some other url , you have to do that in the Javascript Section Using

Ajax update textarea without button or page refresh

I am trying to create a textarea that automatically updates the database without the need to press a button or refresh the page. After a "keyup" occurs there will be a timer that will countdown for 2 seconds. If no other input is made within those 2 seconds then that the data should be updated in the database. If a input is made the timer will restart.
I've written the ajax code below, it doesn't seem to work.
$(document).ready(function() {
var timer;
$('#about').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#about").submit()
alert(value);
}, 2000);
});
var about = $('#about').val().trim();
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: about
},
success: function(response) {
$('#cid').val(response);
}
});
});
/* This is comment.php */
<?php
session_start();
require_once 'config/config.php';
require_once 'includes/auth_validate.php';
$cid = $_GET['customer_id'];
$about = $_POST['about'];
$sql = ("UPDATE patient_id SET about = ? WHERE id = ?;");
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "si", $about, $cid);
mysqli_stmt_execute($stmt);
?>
Move the ajax into the timeout, rather than performing the submit, since you want to update with ajax.
$(document).ready(function() {
var timer;
$('#about').on('input', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
alert(value);
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: value
},
success: function(response) {
$('#cid').val(response);
}
});
}, 2000);
});
});

Ajax not getting only json output data (it print whole loaded view code.).? codeigntier

Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)

CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

How do you input javascript variable into php script?

I'm trying to get a function called that calls a php function with an input.
javascript function (picNum is an integer):
function hello(picNum) {
var pictureNumber = picNum;
var phpFunc = "<?php
include 'otherfile.php';
otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through
?>";
echo phpFunc;
}
otherfile.php
<?php
function otherFileFunc($i) {
$final = $i + 1;
echo $final;
}
?>
this code pretty much says if you do onclick="hello(1)" then the output or phpFunc should be 2 because you add one in the otherfile.php, but no matter the input the output is always 1 so I'm guessing the input at where I marked just isn't going through.
DONT TELL ME IT DOESNT WORK BECAUSE IT DOES.
if i put an integer instead of " + pictureNumber + " it works perfectly!
any help is appreciated :)
Unfortunately you won't be able to call php from javascript.
Php is run from the server and javascript is run on a client (usually, the exception being node.js. However even in the instance of node.js, php is not used as javascript has replaced its functionality)
If you need to have javascript "call" a server function you will need to look into ajax requests so that the server can then run a function and return it to the client.
You have to use Ajax bro:
Javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
}
PHP otherfile.php:
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
Note: Untested
EDIT, tested:
javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
pictureNumber = output_string['picturenumber'];
alert(pictureNumber);
}
});
}
hello(1); //sample
PHP otherfile.php:
$picNum = $_POST['picNum'];
$picNum = 1;
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = otherFileFunc($picNum);
$array = array('picturenumber' => $outputnumber);
echo json_encode($array);

Categories

Resources