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.
Related
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 :)
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() ?>
I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>
I want to use javascript variable in php function.. my code is as below
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
alert('<?php echo getYoutubeDurationV3("<script>document.write(video_val);</script>"); ?>');
});
});
I want to use video_val variable in php function.. how can i do that ?
You can use Ajax for this solution. When you place your PHP getYoutubeDurationV3 function in a .php file.
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
$.ajax({
url: 'yourphpscript.php',
data: {duration: video_val},
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
And in your PHP file you can get the value like this:
<?php
$duration = $_POST['video_val'];
//rest of your logic, in your case your function
//return your response back to your webpage.
return $response;
?>
yes, u can do that by ajax post method..
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
$.ajax({
url: 'ajax_file.php',
data: {duration: video_val},
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
And in ajax_file.php write below code..
<?php
$duration = $_POST['video_val'];
return $duration ;
?>
The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}
Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}