Hide button if number is less than 0 - php

I am trying to hide button if the number is <= 0.
My code:
<?php
$sst = $user->runQuery("SELECT * FROM students_records WHERE LRN=:uID AND SRN=:sd");
$sst->bindparam(":uID",$id);
$sst->bindparam(":sd",$srn);
$sst->execute();
$sstRow=$sst->fetch(PDO::FETCH_ASSOC);
$dsst = $sstRow['Date'];
$sdsst = strtotime($dsst);
echo "
<script>
var checkStatet = function(){
jQuery.ajax({
url: 'q_check_diffex.php?od=$sdsst'
}).done(function(data){
var button1 = jQuery('#rbtntimep');
var o = data.diffex;
var time = jQuery('#rbtntime');
var timer = setInterval(function() {
time.html(o);
o--;
if(data.diffex <= 0) {
button1.hide();
jQuery('#quizsb').click();
}
}, 1000)
});
}
checkStatet();
</script>
"
?>
<button class="btn btn-large btn-primary" id="rbtntimep" style="float:right;" disabled><span id="rbtntime"></span></button>
q_check_diffex.php:
<?php
header('Content-Type: application/json');
if(isset($_GET['od'])){
$deotd = $_GET['od'];
}
date_default_timezone_set('Asia/Calcutta');
$cdate = date('Y-m-d H:i:s ', time());
$scdate = strtotime($cdate);
$rscdate = $scdate + 10;
$e = $rscdate - $deotd;
// You would calculate a real value here
echo json_encode([
'diffex' => $e
]);
?>
I tried the above code but it do not hide the button if <= 0

you are getting the response in JSON from q_check_diffex.php
So, before using var o = data.diffex;, you need to convert the response into object.
Just add the following code right after done(function(data){
data = JSON.parse(data);
Now you can fetch the values like you are using in the code var o = data.diffex;

Related

PHP Google Charts causes for loop to loop weirdly

I am facing an issue where the for loop loops properly to display a table in php when Google Charts is not used and when Google Charts is implemented on the page, the table only loops twice. I know this because I've echoed the count($arr) and echo the word LOOPED. My count shows 9 but it will only loop twice.
The google chart I am using is the pie chart and when this pie chart becomes really huge, where there are many slices, this would occur. What's weird is the Google Chart isn't inside this for loop.
for ($i = 1; $i < count($arr); $i++){
print_r(count($arr));
echo "LOOPED";
$splitwords = explode("ON", ($arr[$i]));
<td>$splitwords[0]</td>
<td>$splitwords[1]</td>"; }
This is the function being called.
function retrievepieCharts(minnumber,hournumber,daynumber){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawminuteChart);
google.charts.setOnLoadCallback(drawhourChart);
google.charts.setOnLoadCallback(drawdayChart);
function drawminuteChart() {
var data = google.visualization.arrayToDataTable([
['Timing', 'Times'],
<?php
for ($i = 0; $i < count($minuteArray); $i++) {
$firstArraywithin10mins = $minuteArray[$i];
$firstDATEtoRetrieve = $firstArraywithin10mins[0];
$firstTimingtoRetrieve1 = $firstArraywithin10mins[1];
$firstTimingtoRetrieve = $firstDATEtoRetrieve . " ". $firstTimingtoRetrieve1;
$totalCountwithin10mins = count($firstArraywithin10mins)-1;
echo "['$firstTimingtoRetrieve', $totalCountwithin10mins],";
}
echo" ]);";
?>
var mintitle = "Logon Fails > 5 within " + minnumber + " minute(s)";
var hourtitle = "Logon Fails > 5 within " + hournumber + " hour(s)";
var daytitle = "Logon Fails > 5 within " + daynumber + " day(s)";
var options = {backgroundColor: 'transparent',chartArea:
{left:0,top:90,width:"90%",height:"90%"}
,height: 450
,width: 450,
title: 'Logon Fails > 5 within '+ minnumber +' minutes (Likely to be automated brute force)'
};
var minutechart = new google.visualization.PieChart(document.getElementById('piechart'));
minutechart.draw(data, options);
function selectminuteHandler() {
var selectedItem = minutechart.getSelection()[0];
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
var date = new Date(topping).toLocaleDateString("en-US");
var options = { hour12: false };
var time = new Date(topping).toLocaleTimeString('en-US', options);
var rows = document.querySelectorAll('#csv_table tr');
$allRows = $('#csv_table tr');
$allData = $('#csv_table td');
row1 = $allRows.filter(function(){
return $.trim($(this).find('td').eq(1).text()) == date;
});
row2 = $allData.filter(function(){
return $.trim($(this).find('td').eq(1).text()) == time;
});
index = $allRows.index(row1);
var table = document.getElementById("csv_table");
row = table.rows[index];
for (var i = 0, row11; row11 = table.rows[i]; i++) {
for (var j = 0, col; col = row11.cells[j]; j++) {
row11.cells[j].style.backgroundColor = "";
}}
rows.forEach(row => row.classList.remove('active'))
for (var j = 0, col; col = row.cells[j]; j++) {
var timeintable = row.cells[j].innerHTML.slice(12,20);
var target = new Date("1970-01-01 " + time);
var target2 = new Date("1970-01-01 " + timeintable);
timedifferences = target - target2;
var minuteVal = timedifferences / 60000;
if (minuteVal< 0){
minuteVal = minuteVal * -1;
}
if (minuteVal < minnumber){
row.cells[j].style.backgroundColor = "yellow";
document.getElementById('msg_div').innerHTML = hourtitle;
rows[index].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
else{
row.cells[j].style.backgroundColor = "";
}
}
}
}
google.visualization.events.addListener(minutechart, 'select', selectminuteHandler);
}
This is the part where the function is being called. The $minData and $hourData is retrieved when the user clicks on the submit button through a form.
if (isset($minData) and isset($hourData)){
echo "<script type='text/javascript'>retrievepieCharts('$minData', '$hourData', '$dayData');
</script>"
;
}
This is the form which takes in the $minData and $hourData. I've tried changing the $minData and $hourData values and every time I changed it, the table loops differently. I've also tried to remove the submit button to see if that was causing the issue but the result is the same without the submit.
<form id="differencesnumber" method="POST">
<label for="mindiff">Minutes Differences</label>&nbsp&nbsp
<input type="number" id="mindiff" name="mindiff" style="width:50px;" min="0"
oninput="validity.valid||(value='');"required>
<br>
<label for="hourdiff">Hours Differences</label>&nbsp&nbsp
<input type="number" id="hourdiff" name="hourdiff" style="width:50px;" min="0" oninput="validity.valid||(value='');"required>
<br>
<input type="submit" value="Get PieCharts">
</form>
The codes are over 1000 lines and if anyone needs the entire code, do inform me.
Anyone knows what is the bug? I've been trying to debug this for days but to no avail.

Ajax reload frame only works once

I have a timetable on my website. The user can select multiple times. The selected time is inserted into the database and the button turns from green to red, so the user know it's disabled.
I want to do this with only a reload of div.
It does work but it work only once, when pushing the button for the second time the div doesn't refresh / reload.
Update database / refresh;
$('.updateTime').click(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
var uniqueId = $(this).attr('id');
var sdate = getUrlParameter('date');
$.ajax({
url: './ajax/reservation_insert_times.php',
type: 'POST',
data: {
uniqueId :uniqueId, sdate :sdate
},
success: function(mydiv){
$("#result").load(location.href+ ' #mydiv');
}
});
});
The code for generating the times
<div class="row" id="result">
<?
$result = array();
$query = $db->query("SELECT * FROM reservation_times WHERE datum = '" . db_escape($_GET['date']) . "' ");
while($row = mysqli_fetch_array($query)) {
$result[] = $row['time'];
}
?>
<?
$timestamp = strtotime(date("Y-m-d")." 12:00");
for ($i=0;$i<=32;$i++) {
$time = date('H:i', $timestamp);
$time .= ' UUR';
if (in_array($time, $result)) {
$color = "background-color:red !important";
}
else $color = "";
$timestamp += 15 * 60;
if (isset($checked) && $checked !='') { $color = 'background-color: red;';}?>
<div class="col-xs-4 col-md-3 col-lg-2" id="mydiv">
<button type="button" id="<?=$time;?>" class="btn btn-block btn-success btn-sm text-center" style="padding:10px; margin-bottom:10px; <?=$color;?>" onclick="" <? if (isset($checked) && $checked !='') { echo 'disabled';}?>>
<?=$time;?>
</button>
</div>
<? } ?>
</div>
The code for the reservation_availablity.php call:
$query = $db->query("SELECT * FROM reservation_times WHERE time = '".$uniqueId."'");
if(mysqli_num_rows($query) == 1) {
$remove = $db->query("DELETE FROM reservation_times WHERE time = '".$uniqueId."'");
} else {
if (isset($uniqueId) && $uniqueId !='') :
$sql = $db->query("INSERT INTO reservation_times (time, datum)
VALUES ('".$uniqueId."', '".$newDate."')");
endif;
}
Change you success method of your ajax:
$.ajax({
url: './ajax/reservation_insert_times.php',
type: 'POST',
data: {
uniqueId :uniqueId, sdate :sdate
},
success: function(mydiv){
$("#result").html(mydiv);
}
});
You are sending an ajax to get new content but then in success method instead of loading new content received as ajax response you are again loading the content of the same div. That's why it is working for the first time but will remain unchanged next time onwards.
//Wrong
$("#result").load(location.href+ ' #mydiv');
// Correct
$("#result").html(mydiv);
So, now whenever this ajax send to the server, it will update the content of div#result. And to allow user to manually refresh the content of this div as and when desired then you will have to call this ajax upon click of a button labled as Refresh Timetable.

jquery php mysql - how to hide load more button when all itemes displayed

I have a code for showing list from database and a loadmore button. After all records list is displayed and click on loadmore button show empty places.
How to hide loadmore button once all records displayed?
index.php file:
<?php $chinp=$_GET['schinp'];?>
<div id="schts"></div>
<button id="btnsch">load more</button>
<script>
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 1;
var offsrch = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp}
})
.done(function(msg) {
$("#schts").append(msg);
});
offsrch = offsrch + srchco;
});
$("button").trigger("click");
});
</script>
search.php :
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
Thanks.
Here is code to hide load more button as per your code.
Replace this code in your first file.
<script type="text/javascript">
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 2;
var offsrch = 0;
var page_num = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp, page_num : page_num}
})
.done(function(msg) {
if(msg == 'noMoreData'){
$("#btnsch").hide();
} else {
$("#schts").append(msg);
}
});
page_num = page_num + 1;
offsrch = offsrch + srchco;
});
$("#btnsch").trigger("click");
});
</script>
Now add this code in your search file.
<?php
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$page_num=$_POST['page_num'];
$total_records = 0;
$totalschql="SELECT id FROM t_users WHERE name LIKE 'krishna' ORDER BY name ASC";
if ($result=mysqli_query($conn,$totalschql))
{
$total_records=mysqli_num_rows($result);
}
$last_records_count = ($page_num) * $srchcoun;
if($last_records_count >= $total_records) {
echo 'noMoreData';exit();
} else {
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";;
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];
?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
<?php
}
?>
Try this and let me know if you have any issue.
Simply use $('#myButtonId').hide(); in ajax part after you load the entire data from database.
function get_rain_data_list(is_load_more=0){
if(is_load_more!=0){//if is_load_more is not 0 then get offset data from btnlod attr
offset = $('#btn_load_more_rain').attr("data-offset");
}else{ //set offset =0 when is_load_more is 0
offset = 0;
}
var id = $('#id').val();
var countShow = 0;
if(fromDate!=''){
countShow = 1;
}
$.ajax({
url: base_url+"rain_data_list_ajax",
type: "POST",
data:{offset:offset,propertyId:propertyId,fromDate:fromDate,toData:toData},
dataType: "JSON",
beforeSend: function() {
show_loader();
},
success: function(data){
hide_loader();
// console.log(data);
$('.proprty_load_more_btn').remove();//remove load more button
if(offset==0){ //clear div when offset 0
$("#append_rain_list").html('');
}
if(data.no_record==0){//show data in div when no previous record
$("#append_rain_list").html(data.html_rain);
$("#add_count").html('');
if(countShow){
//$("#add_count").html(data.count+data.record);
}
}else{
//append data when already record show in view
$("#append_rain_list").append(data.html_rain);
$("#append_load_btn").append(data.btn_html);
$("#add_count").html('');
if(countShow){
$("#add_count").html(data.count+data.record);
}
}
},
});
}
<div id="append_rain_list"></div>
<div id="add_count"></div>
<?php
function rain_data_list_ajax(){
$limit = 6;
$is_next = 0;
//get and set offset
$offset = $this->input->post('offset');
$data['property_id'] = decoding($this->input->post('propertyId'));
$fDate = sanitize_input_text($this->input->post('fromDate'));
$tDate = sanitize_input_text($this->input->post('toData'));
$new_offset = $limit+$offset; //pr($data);
//set where
$where = array('property_id'=>$data['property_id']);
//set select field to get
$data['limit'] = $limit;
$data['offset'] = $offset;
//get count of records
$dataView['total_count'] = $this->Property_model->get_rain_count($data);
//get records
$dataView['rain_list'] = $this->Property_model->get_rain_list($data);
///lq();
//check for load more btn
//pr($dataView);
if($dataView['total_count']>$new_offset){
$is_next =1;
}
$btn_html = '';
if($is_next){
//if is next =1 set load more button in btn_html
$id = "btn_load_more_rain";
$btn_html = '<div class="col-sm-12 text-center pt-20 proprty_load_more_btn"><button class="login-btn load load_more_btn" id = "'.$id.'" data-offset ="'.$new_offset.'" data-isNext ="'.$is_next.'" >'.lang('load_more').'</button></div>';
}
//load view with data
$html_rain = $this->load->view('test1',$dataView,true);
$response = array('status'=>1,'html_rain'=>$html_rain,'btn_html'=>$btn_html,'count'=>$dataView['total_count'],'record'=>lang('recod_found'));
//flag for no record
$no_record=1;
if(empty($dataView['rain_list'])){
$no_record = 0;
}
$response['no_record'] = $no_record;
echo json_encode($response);die;
}
?>

Convert data to Json in CodeIgniter with AJAX

I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);

How to to output json into a div

Consider the following PHP Block. I want to output "name" to div #1 and "slog" to div #2
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['name'] = $row['name'];
$result['slog'] = $row['slog'];
echo json_encode($result);
}
mysql_close($con);
?>
Here's the ajax that just outputs json itself.
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
};
})();
get_fb();
You can update the html/content of a DOM element with the following:
document.getElementById(name).innerHTML = "text";
So in this instance:
document.getElementById('#1').innerHTML = $yourNameContent;
document.getElementById('#2').innerHTML = $yourSlogContent;
First: move var counter = 0; outside from get_fb() function;
Second: Do not call get_fb(); explicitly, because (function(){...})(); already calls method after initialization.
Third: Why use POST method if there is not data to submit!
So, do this and have a try:
var counter = 0;
var $buzfeed = $('#BuzFeed');
var get_fb = (function() {
$.ajax({
type: "GET",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
})();

Categories