Ajax reload frame only works once - php

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.

Related

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;
}
?>

Hide button if number is less than 0

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;

Populating html table from external php to allow highlighting on hover over row

I am trying to populate a html table based on a select box (with staff numbers) changing. The data is being retrieved from a mysql database. I then want to highlight a row when it is hovered over using jquery.
Am I going about this the right way?
main.php
<div id="logHistory">
<label id="historyTableLabel">Your Log History</label>
<table id="logTable">
<tr id="headers">
<td>Log Date</td>
<td>LogType</td>
<td>Start Time</td>
<td>End Time</td>
<td>Duration</td>
</tr>
</table>
</div>
select.php
$staffNum = isset($_POST['staffNumber']) ? $_POST['staffNumber'] : 0;
if($staffNum > 0)
{
populateLogHistory($con, $staffNum);
}
function populateLogHistory($con, $staffNum)
{
//Retrieve data from entries table
$result = mysqli_query($con, "SELECT EntryID, LogDate, LogType, StartTime, StartDate, FinishTime, FinishDate FROM Entries WHERE StaffNumber=$staffNum");
while($row = mysqli_fetch_array($result))
{
$entryID = $row['EntryID'];
$logDate = $row['LogDate'];
$logTypeID = $row['LogType'];
$resulting = mysqli_query($con,"SELECT LogType FROM logType WHERE LogTypeID=$logTypeID");
$logTypeStr = mysqli_fetch_array($resulting);
$startDate = $row['StartDate'];
$startTime = $row['StartTime'];
$start = $startDate . " " . $startTime;
$start = new DateTime($start);
$finishDate = $row['FinishDate'];
$finishTime = $row['FinishTime'];
$finish = $finishDate . " " . $finishTime;
$finish = new DateTime($finish);
$duration = $start->diff($finish);
echo "<tr id=".$entryID.">";
echo "<td>".$logDate."</td>";
echo "<td>".$logTypeStr[0]."</td>";
echo "<td>".$startTime."</td>";
echo "<td>".$finishTime."</td>";
echo "<td>".$duration->h."hr ".$duration->i."</td>";
echo "</tr>";
}
}
jquery code
$(document).ready(function()
{
$("#staffMember").change(function()
{
//Check the mandatory first
var selectedIndex = $("#staffMember").prop('selectedIndex');
isMandatory(selectedIndex, $(this));
if(selectedIndex != -1)
{
//If there is a staff number call the select to populate the log history
var staffNum = $("#staffMember").val();
var dataString = 'staffNumber=' + staffNum;
$.ajax({
type: "POST",
url: "select.php",
data: dataString,
cache: false,
success: function(html)
{
$("#logTable").html(html);
}
});
}
}).change();
});
Use this CSS for the hovering part:
.datarow:hover {
background-color: #ccc;
}
Assuming that you put a class tag to your populated row:
echo '<tr id="'.$entryID.'" class="datarow">';
For the populating part, use .on() for every call so you can still do another call on Javascript DOM elements.
$(document).on("change", "#staffMember", function(){
And if you want to do another event handler on the populated data, let's put it as a class tag instead and the data ($entryID) will be on another data tag.
echo '<tr data-artid="'.$entryID.'" class="datarow">';
So when you try to call it, you can just do:
$(document).on("click", ".datarow", function(){
var entryid = $(this).attr('data-artid'); /* ENTRY ID OF THE CLICKED ROW */

Load the next 10 record via Ajax Search Box using PHP MySQL and JQUERY

I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . Wİthout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;

ajax json response array using in php

I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />​​​​​​​​​​​​​​​​​
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.

Categories