how do we disable the button when all posts are loaded ?
all post loaded = button disabled or hide
or show another way ajax load more pagination codeigniter :(
I know little english sorry
Controller
public function getCountry(){
$page = $_GET['page'];
$this->load->model('posts_model');
$posts = $this->posts_model->getCountry($page);
foreach($posts as $post){
echo "<h3>".$post->post_title."</h3><td>".$post->post_content."</td>";
}
exit;
}
Model
public function getCountry($page){
$offset = 2*$page;
$limit = 2;
$sql = "select * from posts limit $offset ,$limit";
$result = $this->db->query($sql)->result();
return $result;
}
Script
<script>
$(document).ready(function(){
getcountry(0);
$("#load_more").click(function(e){
e.preventDefault();
var page = $(this).data('val');
getcountry(page);
});
});
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>welcome/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#ajax_table").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
});
};
var scroll = function(){
$('html, body').animate({
scrollTop: $('#load_more').offset().top
}, 1000);
};
</script>
In your get country function you can do like this. so whenever you get the empty results it means no more result available and your button will be disabled.
<script>
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>welcome/getCountry",
type:'GET',
dateType:'json',
data: {page:page}
}).done(function(response){
if(response.result == 'success') {
$("#ajax_table").append(response.data);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
} else {
$("#load_more").prop('disabled',true);
}
});
};
</script>
In your controller make this changes
public function getCountry(){
$page = $_GET['page'];
$this->load->model('posts_model');
$posts = $this->posts_model->getCountry($page);
$response = array();
$data = '';
if(!empty($posts)) {
foreach($posts as $post){
$data .= "<h3>".$post->post_title."</h3><td>".$post->post_content."
</td>";
}
$response = array('result'=>'success','data'=>$data);
} else {
$response = array('result'=>'error');
}
echo json_encode($response)
}
Related
I am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I am inserting data successfully by selecting multiple row table data but at the same time I want to print data on print page.
In above image I select only 3 record and insert in data base at the time of insert that selected data I want show on my print page.
Create page:
<form>
<table id="pending_collection_table"> </table>
<input type="button" id="allocate" value="allocate" name="allocate">
</form>
<script>
$('#allocate').click(function (event) {
event.preventDefault();
var allVals = [];
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
});
var formData = new FormData();
var agent = $('#agent').val();
var rec_type = $('#rec_type').val();
formData.append("agent",agent);
formData.append("rec_type",rec_type);
for (var i = 0; i < allVals.length; i++) {
formData.append('due_ids[]', allVals[i]);
}
alertify.confirm('Payment Recovery Allocation', 'Do you want to Allocate ?', function(){
$.ajax({
url :"<?php echo base_url();?>crossing/payment_rec_allocation/PaymentRecAllocationController/createPaymentAllocation",
type:"POST",
dataType: "json",
data:formData,
contentType:false,
cache:false,
processData:false,
success: function(data){
if(data.PaymentRecAllocation.form_status=='false'){
}
else if(data.PaymentRecAllocation.form_status=='true'){
alertify.confirm('Payment Recovery Allocation', 'Do you want to print ? ', function(){
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
setTimeout(location.reload.bind(location), 2000);
},
function(){
location.href="<?php echo base_url(); ?>", 'refresh';
});
}
}
});
}, function(){
});
});
</script>
Contoller:
public function createPaymentAllocation()
{
$bilty_ids = $this->input->post('due_ids');
$biltyCount = count($bilty_ids);
$agent = $this->input->post('agent');
$due_to = $this->input->post('due_to');
for($i = 0; $i < $biltyCount; $i++) {
$data = array(
'agent_id' =>$agent,
'pay_dueto' =>$due_to,
'mr_no' =>$bilty_ids[$i],
);
$modelResult = $this->PayRecAllModel->inserPaymentAllocation($data);
}
if($modelResult){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate'
);
}else{
$data['PaymentRecAllocation'] = array(
'form_status' => 'false',
'form_message' => 'Something went wrong.'
);
}
echo json_encode($data);
}
Model:
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
return true;
}else {
return false;
}
}
And now my print function on controller
public function printCollectionRecPage(){
$this->load->view('template/header');
$data= array();
$data['collnR'] = $this->PayRecAllModel->printCollectionRecPage();
$this->load->view('crossing/payment_rec_allocation/printCollectionRecovery',$data);
$this->load->view('template/footer');
}
model of print page:
public function printCollectionRecPage(){
$this->db->select('*');
$this->db->from('payment_rec_allocn');
$this->db->join('crossing_cash_memo', 'payment_rec_allocn.mr_no = crossing_cash_memo.mr_no');
$this->db->where('total !=','0');
$query = $this->db->get();
return $query->result();
}
How I can pass ids in print page.
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
How can I pass that selected ids on print page.
And my print page I have table to show data of selected data on inset time.
You can use insert_id() function
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}else {
return false;
}
}
store returned ids into array
$modelResult[] = $this->PayRecAllModel->inserPaymentAllocation($data);
if(!empty($modelResult)){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate',
'form_ids' => $modelResult
);
}
Pass the ids to your controller for print
var ids = data.PaymentRecAllocation.form_ids.join(',');
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage?ids="+ids;
But in case of multiple inserts you should ideally use
$this->db->trans_start();
//all your insertion code here
//if anything breaks the db will be rollback
$this->db->trans_complete();
I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
I have status active/Deactive Buttons when user clicks on active status it turns into deactive with red color and vice versa
currently i'm able to update my status #backend but everytime i should refresh to see my changes!!
my requirement is during active/deactive process of changing status i want to load ajax image loader where loader image should overlay entire screen. and my status should be updated in mysql db!!
please any help is appricated Thanks!
Php Code
<?php
include 'db.php';
$sql = "select * from sections order by id asc";
$data = $con->query($sql);
$str='';
if($data->num_rows>0)
{
while( $row = $data->fetch_array(MYSQLI_ASSOC))
{
$str.="
"?>
<div class="row">
<div class="col-md-1">
<?php
if ($row['status'] == '1')
{
?>
<a href="#" class="btn btn-success btn-sm active" ida='<?php echo $row['id'];?>'></a>
<?php }
else if($row['status'] == '0')
{
?>
<a href="#" class="btn btn-danger btn-sm deactive" idde='<?php echo $row['id'];?>'></a>
<?php } ?>
</div>
</div>
<?php
}
}
else
{
$str .= "<p style='text-align:left;'>No Data Available</p>";
}
echo $str;
?>
Jquery Code
<script type="text/javascript">
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
$('body').delegate('.deactive','click',function(e){
var IdStatus = 1;
var id = $(this).attr('idde');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
</script>
PHP Updation Code
<?php
if(isset($_REQUEST['status']))
{
$status = $_REQUEST['status'];
$id = $_REQUEST['id'];
$sql = 'update sections set status='.$status.' where id='.$id.'';
$result = mysql_query($sql);
if($result)
{
echo 'updated successfully';
}
else
{
echo 'failed to update';
}
}
?>
Try this script with mentioned changes:
Changes:
Keep same attribute as data-id for both the operations
loaderElem will be the loader container which should be there in your DOM
BODY is nothing but a body selector, just to avoid redundant selectors
var elem = $(this); is used as I need this reference after success callback
Also make habit of using error callback as you might need to handle that case
var BODY = $('body');
var loaderElem = $('#loader');
BODY.delegate('.active', 'click', function(e) {
loaderElem.show();
var IdStatus = 0;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('active').addClass('deactive');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
BODY.delegate('.deactive', 'click', function(e) {
loaderElem.show();
var IdStatus = 1;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('deactive').addClass('active');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
Try using beforeSend option of $.ajax()
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
beforeSend: function() {
// do overlay stuff
},
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
// remove overlay stuff
alert('success');
}
});
e.preventDefault();
return false;
});
<button id="survey_act" method="post" class="tiny ui blue button" type="button" value="<?php echo $surv['id']; ?>" >Activate Survey</button>
This is my button on click -
<script>
$(document).ready(function(){
$(document).on("click","#survey_act", function(){
alert(this.value);
idx = this.value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/admin/survey/act_surveyby_id/')?>/"+idx,
}).done(function(msg){
if(msg=="success"){
alert('You Successfully Activated the Survey!');
}
});
});
});
</script>
This is my javascript -
public function act_surveyby_id($id){
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id)){
echo "success";
}else{
echo "invalid";
}
}
This is my controller -
public function insert_activate($id){
$date = date('m-d-Y',now());
$stat = 'Active';
$data = array(
'issued_date' => $date ,
'status' => $stat
);
$this->db->update('survey', $data)->where('survey_id', $id);
if($this->db->affected_rows()>0){
return true;
}else{
return false;
}
}
}
This is my model -
Problem: when i click the activate survey it wont change/update the details of the survey. I really badly need a help regarding with this. Thanks . . .
change $.ajax function like below
$.ajax({
url: '<?php echo base_url(); ?>index.php/admin/survey/act_surveyby_id',
type: "POST",
data: {
idx : idx;
},
and controller like below
public function act_surveyby_id(){
$id=$_POST['idx'];
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id))
{
echo "success";
}else{
echo "invalid";
}
}