Zabuto Calendar with ajax - php

How can I get the events stored in my db to show in the calendar ?
I can't seem to figure out how to replace the random dates with my own ones :/
Basically I have to loop through the data i get from my db don't I ?
And put the data in the JSON format ...
Can I use a foreach loop ?
this is the code provided by the zabuto calendar download site
<?php include_once 'includes/sessions.php'; ?>
<?php include_once 'includes/connect.php';
/**
* Example of JSON data for calendar
*
* #package zabuto_calendar
*/
if (!empty($_REQUEST['year']) && !empty($_REQUEST['month'])) {
$year = intval($_REQUEST['year']);
$month = intval($_REQUEST['month']);
$lastday = intval(strftime('%d', mktime(0, 0, 0, ($month == 12 ? 1 : $month + 1), 0, ($month == 12 ? $year + 1 : $year))));
$dates = array();
for ($i = 0; $i <= (rand(4, 10)); $i++) {
$date = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-' . str_pad(rand(1, $lastday), 2, '0', STR_PAD_LEFT);
$dates[$i] = array(
'date' => $date,
'badge' => ($i & 1) ? true : false,
'title' => 'Example for ' . $date,
'body' => '<p class="lead">Information for this date</p><p>You can add <strong>html</strong> in this block</p>',
'footer' => 'Extra information',
);
if (!empty($_REQUEST['grade'])) {
$dates[$i]['badge'] = false;
$dates[$i]['classname'] = 'grade-' . rand(1, 4);
}
if (!empty($_REQUEST['action'])) {
$dates[$i]['title'] = 'Action for ' . $date;
$dates[$i]['body'] = '<p>The footer of this modal window consists of two buttons. One button to close the modal window without further action.</p>';
$dates[$i]['body'] .= '<p>The other button [Go ahead!] fires myFunction(). The content for the footer was obtained with the AJAX request.</p>';
$dates[$i]['body'] .= '<p>The ID needed for the function can be retrieved with jQuery: <code>dateId = $(this).closest(\'.modal\').attr(\'dateId\');</code></p>';
$dates[$i]['body'] .= '<p>The second argument is true in this case, so the function can handle closing the modal window: <code>myFunction(dateId, true);</code></p>';
$dates[$i]['footer'] = '
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="dateId = $(this).closest(\'.modal\').attr(\'dateId\'); myDateFunction(dateId, true);">Go ahead!</button>
';
}
}
echo json_encode($dates);
} else {
echo json_encode(array());
}

Related

After ajax request php function not receiving variables

I'm developing a searcher and I made a function that gets the data from a db, saves each ad in a variable and saves pagination (from another function) in another variable, so they can be returned in an array to be printed in the html later.
It works like this: you hit a buy or rent button and you go to the search page (/search?do?=buy/rent) then you have to select the property type, optionally a city/zone and hit search. Ajax sends the data via post (to search.php, the same file), hides the first container and shows the second container that has the list of properties with a pagination at the end of the page.
These are the main variables and a script to hide/show containers:
$mode = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent
$prop_type = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX
$zone = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX
$page_number = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);
if (isset($page_number) && $page_number >= 1) {
$cont1 = 'display: none;';
$cont2 = NULL;
// need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET.
} else {
$cont1 = NULL;
$cont2 = 'display: none;';
}
This is the function:
function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) {
if ($prop_type == 'res') {
$table2 = 'res_prop';
} else if ($prop_type == 'com') {
$table2 = 'com_prop';
}
if ($city != 0) {
$optional_cond = ' WHERE t2.city = ' . $city;
$optional_cond2 = NULL;
if ($zone != 0) {
$optional_cond2 = ' AND t2.zone = ' . $zone;
}
} else $optional_cond = $optional_cond2 = NULL;
$mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name');
// pagination
if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) {
$stmt->execute();
$stmt->bind_result($totalitems);
$stmt->fetch();
if (!isset($page)) {
$page = (int)$page_number <= 0 ? 1 : (int)$page_number;
}
$limit = 4;
if ($page > ceil($totalitems / $limit)) {
$page = ceil($totalitems / $limit);
}
$start = ($page - 1) * $limit;
$stmt->close();
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id
' . $optional_cond . $optional_cond2 . '
LIMIT ?, ?')) {
$stmt->bind_param('ii', $start, $limit);
$stmt->execute();
$stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4);
$test = "";
while ($row = $stmt->fetch()) {
if ($status === 0) {
$possesion = 'En construcción';
} else if ($status === 1 || $status === 2) {
$possesion = 'Inmediata';
} else $possesion = 'Desconocida';
if ($prop_type == 'res') {
$is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p>
<p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>';
} else $is_res = NULL;
$test .= '<div class="box-col">
<div class="col-sm-6 left-side ">
<img class="img-responsive" src="' . $img1 . '" alt="">
</div>
<div class="col-sm-6 middle-side">
<h4>Disponibilidad: ' . $possesion . '</h4>
' . $is_res . '
<p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p>
<p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p>
<p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p>
<p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p>
<div class="right-side">
Contact Builder
</div>
</div>
<div class="clearfix"> </div>
</div>
';
$pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page=");
}
} //else echo "Statement failed: " . $mysqli->error . "<br>";
} //else echo "Statement failed: " . $mysqli->error . "<br>";
return array($test, $pagination);
}
This is the main code:
if (empty($_GET)) {
echo 'under construction';
}
else if (isset($mode) && $mode == 'buy') {
$table = 'to_sell';
$targetpage = '/search?do=buy';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else if (isset($mode) && $mode == 'rent') {
$table = 'to_rent';
$targetpage = '/search?do=rent';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else {
echo 'invalid url';
}
This is the AJAX script that sends the checkbox value via post (it's not working correctly, I don't get an undefined error in $prop_type (I don't know why???) but I get it in $table2, that it's inside the if ($prop_type == '')):
$('.search, .pagination').click(function() { // search button and change page
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.post('search.php', { // same file, maybe self
prop_type: $prop_type,
city: $('select[name=city]').val(), // optional
zone: $('select[name=zone]').val(), // option value="0" by default
success: function(){
$('.cont-1').hide();
$('.cont-2').show();
}
});
});
It works perfectly if I manually set $prop_type = 'res';. Any ideas?
Another problem is that the pagination buttons link does not work, it just triggers the ajax script (they need to send the data, otherwise the script will restart when changing pages).
I really would appreciate any optimization to the scripts. Thanks.
You're mixing your javascript and php here.
In PHP you declare a variable with $varname, in Javascript, $ represents the jQuery operator. As such your code that says $prop_type is totally invalid since this is javascript code. You're telling jQuery to execute some functionality called prop_type which doesn't exist, and as such you're getting an error that this is undefined.
if ($('#res_prop').is(':checked')) {
var prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var prop_type = $('#com_prop').val();
}
And change the line which reads prop_type: $prop_type, to prop_type: prop_type,
If you want to import the <div class="results"></div> container with ajax:
you should use this tested and working code:
$(document).ready(function(){
$('.search, .pagination').click(function() { // search button and change page
$prop_type = '';
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.ajax({
method: "POST",
url: "go.php",
data: {
'prop_type': $prop_type,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val()
}
}).done(function(data) {
var _html = $.parseHTML(data);
$('.cont-1').hide();
$('.cont-2').show();
$(_html).each(function(i, el) {
if (el.className == 'results') {
$('.results').html($(el).html());
};
});
});
return false;
});
});

Trying to send star ratings from krajee bootstrap star rating to mysql database

I am using the following plugin
http://plugins.krajee.com/star-rating
I'm trying to send the rating submitted to the database but the values are not being recorded.
require_once $doc_root . '/includes/act_initiate_article_xref.php';
$rating_value = (#$user_article_xref_row['rating'] > 0) ? $user_article_xref_row['rating'] . ' stars' : 'unrated';
$article_rating = '<span class="line-sep">Rated:</span> ' . $rating_value;
if ($_SESSION['user_id'] == 1 || $_SESSION['user_id'] == 41) {
$rating_value_attr = (isset ($user_article_xref_row['rating'])) ? ' value="' . $user_article_xref_row['rating'] . '"' : '';
$article_rating .= '<span class="line-sep">Your rating: </span> <input id="input-21d" type="number" class="rating"' . $rating_value_attr . ' data-min=0 data-max=5 step=0.5 data-size="xs">';
}
and the code for act_initiate_article_xref.php
<?
/**
* reads user_article_xref
*/
$this_routine[] = "includes/act_initiate_article_xref.php";
/**
* no direct access allowed
*/
$doc_root = $_SERVER['DOCUMENT_ROOT'];
require_once $doc_root . '/includes/act_check_valid_access.php';
$table_title = 'user_article_xref';
$user_id = (isset ($_SESSION['user_id'])) ? $_SESSION['user_id'] : 0;
$fields = '`id`, `hits`, `rating`';
$match_where = '`user_id` = ' . $user_id . ' and `article_id` = ' . $article_id;
$article_result = $db->selectByStrings($fields, $table_title, $match_where, null, 1);
#if ($_SESSION['user_id'] == 1) { echo "<br>21. select $fields from $table_title where $match_where<pre>";print_r($_SESSION);echo "</pre>"; }
/**
* if there is already a record, update it
* if there isn't already a record, insert it
* either way, $user_article_xref_row holds details for any ajax rating update
*/
if ($db->getNumRows($article_result) > 0) {
$user_article_xref_row = $db->getNextRow($article_result);
$hits = $user_article_xref_row['hits'] + 1;
$pairs_array = array ('hits' => $hits);
$id_where = '`id` = ' . $user_article_xref_row['id'];
$update_result = $db->updateByArray($table_title, $pairs_array, $id_where);
$test = 'update';
} else {
$hits = 1;
$user_article_xref_row = array ('user_id' => $user_id, 'article_id' => $article_id, 'hits' => $hits);
$insert_result = $db->insertByArray($table_title, $user_article_xref_row);
$test = 'insert';
}
#if ($_SESSION['user_id'] == 1) { echo "<br>37. $test<pre>";print_r($user_article_xref_row);echo "</pre>"; }
?>
I know this post is a little old but just in case. In the star-rating.js I added an ajax post to my php file to the set.listenClick function. Hope this helps.
self.listenClick(self.$rating, function(e) {
if (self.inactive) {
return false;
}
pos = self.getPosition(e);
var div_id = self.$element.attr('id');
self.setStars(pos);
self.$element.trigger('change').trigger('rating.change', [self.$element.val(), self.$caption.html()]);
self.starClicked = true;
var rating = self.$element.val();
$.ajax({
type:"POST",
url:"rating.php",
data:"div="+div_id+"&rating="+rating,
success: function(res){
console.log("Rating was posted " + div_id + rating);
return res;
}
});
});

Displaying same time passed in while through time_passed function

I'm doing a while() and in it I use a function to display a prettier "time since posted", but for some reason, all of the results end up in the same "time passed" (the last result) when echoing it out
only the time will become the same, not the other content. Here's my code, trimmed down a bit:
<?php
$result = $db->query("SELECT * FROM $dbboardname WHERE replyto = '' AND hidden = '' ORDER BY bump ASC LIMIT $pagenum, 20") OR die($db->error);
while($rowaaa = $result->fetch_assoc()){
$id = $rowaaa['id'];
$textcontent = $rowaaa['textcontent'];
$imageurl = $rowaaa['imageurl'];
$name = $rowaaa['nameyes'];
$timestamps = $rowaaa['timestamp'];
$timestamps = time_passed($timestamps);
$tripcode = $rowaaa['tripcode'];
?>
<div class="post-index" data-postid="<?php echo($id); ?>" name="<?php echo($id); ?>" id="<?php echo($id); ?>">
<div class="image-container-index">
<?php if(!empty($imageurl)){ ?>
<img src="<?php echo($imageurl); ?>" alt="image <?php echo($id); ?>" />
<?php }else{
?>
<img src="/images/noimage.png" alt="no image" />
<?php
}
?>
</div>
<div class="post-info">
<span class="post-info-left">
#<?php echo($id); ?> by <?php if (!empty($name)){
echo(substr($name, 0, 8));
}else{
echo("norseman");
}
?>
</span>
<span class="post-info-right">
<?php echo($timestamps); ?>
</span>
<div class="clear"></div>
</div>
<div class="post-preview">
<?php echo(substr($textcontent, 0, 150)); ?>
</div>
</div>
<?php
}
?>
<div class="clear"></div>
And here is the time_passed() function:
function time_passed($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
So my guess is that for every new "while", it edits all of the timestamps. I just don't know how to fix this, considering the string is inside an while() statement.
EDIT:
I noticed my timestamp updated because I altered the bump row on every post each time a new thread was posted, this way all the timestamps were updated. I fixed the timestamp row now.
It looks like your time_passed routine is expecting a datetime - not a timestamp, perhaps that is the error.
function time_passed($datetime, $full = false) {
Try to change this line:
$ago = new DateTime($datetime);
to this:
$ago = new DateTime(date('r',$datetime));
I hope that helps.
Let's try this again ... since they are all coming out the same, it sounds like the value you are passing to the function is wrong then - try putting a a test around the timestamp assignment:
$timestamps = $rowaaa['timestamp'];
echo "Made |$timestamps| from |{$rowaaa['timestamp']}<br/>\n";
$timestamps = time_passed($timestamps);
echo "Now timestamps is |$timestamps| from time_passed() function<br/>\n";
If they are all the same, the problem is in your data.
You can also show the entire content of the array by doing this:
echo "Full Details<pre>\n".print_r($rowaaa,1)."\n</pre>\n";

PHP Show options depending on the selected year

I am trying to show options to the user according to the year he's selecting.
At the top of the file I have a function to retrieve the year, and send it back to the same page which is view2.php, but I'm sure I'm doing it wrong:
if(!empty($_POST['year'])){
$year = htmlentities($_POST['year']);
header('Location: view2.php');
//exit();
}
Later, I have a form submitting the year that looks like this
<form method="post" action="">
Select year:
<?php
$myOptions = array(
'All' => 'All',
'2013' => '2013',
'2014' => '2014',
'2015' => '2015',
'2016' => '2016',
'2017' => '2017',
'2018' => '2018',
'2019' => '2019',
'2020' => '2020'
);
?>
<select name="year">
<?php
foreach($myOptions as $key => $opt) {
$selected = null;
if(isset($_POST['View All']) && $key === $_POST['View All'])
$selected = ' selected';
echo '<option value="' . $key . '"' . $selected. '>' . $opt . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="GO"/>
</form>
If I manually set the $year variable, my sql query works fine, so the function ($users->expensePerYear($username, $year, $i);) is okay. This is my function:
<?php
$i=0;
$year = 2013;
//if (isset($year)){
$users->expensePerYear($username, $year, $i);
$userQueryResult = $users->queryResult;
$count = $users->i;
$totalSpent = $users->totalSpent;
$remaining = $budget-$totalSpent;
The problem is that I'm trying to send the year variable to the same page and I'm doing it wrong. I want the user to specify the year in the select, send it to the same page and show stuff according to that variable.
Never mind me, I only had to comment the header() line and it works.
if (isset($_POST['submit2'])) {
$year = htmlentities($_POST['year']);
//header('Location: view2.php?$year=".$year."');
//echo $year;
}

Ajax Paging with php and mysql

I am trying to setup paging on my site using Ajax, I've inherited a script and put it into practice at the following link - http://www.testing.arrivaldesign.co.uk/properties.
I've got it working to an extent, but it's set to show the first 9 records and then carry on from there, but it's only showing the first 9 on the first page, but then when you click to the next page it just repeats 4 of the existing records.
As far as I can see it's to do with limit on my query, but I don't know how to get it working?
This is the code for the ajax side of things.
<?php
include('Connections/connection.php');
include 'functions.php';
// Pagination params
$basePath = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
$qString = $_REQUEST['qString'];
$items = $_REQUEST['items'];
$loadPage = $_REQUEST['p'];
$current = $_REQUEST['current'];
$limit = $loadPage*$items;
$min = ($max-$items)+1;
mysql_select_db($database, $conn);
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, $limit";
$RSproperty = mysql_query($query_RSproperty, $conn) or die(mysql_error());
$row_RSproperty = mysql_fetch_assoc($RSproperty);
$totalRows_RSproperty = mysql_num_rows($RSproperty);
$maxItems = $totalRows_RSproperty;
// New pagination
$pagination = paginator($basePath . $qString, $loadPage, $maxItems, $items);
// Direction is important for the script to determine which way to animate, left or right.
$direction = 'left';
if ($current < $loadPage) {
$direction = 'right';
}
$paginatedStyle = 'style="left:'.($direction == 'left' ? '0' : '-960px').';"';
// The paginated content HTML slide
$page = '<div class="paginated" id="" '.$paginatedStyle.'>';
ob_start();
do {
?>
<div class="grid-1third res-block">
<div class="prop-brief-desc">
<div class="grid-140"><img src="/prop-images/thumbs/<?php echo $row_RSproperty['propImage1']; ?>" width="140" height="105" alt=""></div>
<div class="grid-140 fr">
<h2><?php echo $row_RSproperty['propBeds']; ?> Bed <?php echo $row_RSproperty['typeName']; ?></h2>
<?php
$fulladdress = $row_RSproperty['propAddress1'] . '<br />' . $row_RSproperty['propCity'] . ', ' . $row_RSproperty['propCounty'] . '<br />' . $row_RSproperty['propPostcode'];
?>
<p><?php echo $fulladdress; ?></p>
</div>
</div>
<div class="prop-brief-options<?php echo $no == 2 || $no == 3 ? " hide" : ""; ?>" id="newopt<?php echo $no; ?>">
<div class="grid-140"> Details Arrange Viewing Place Bid Buy it Now </div>
<div class="grid-140 fr">
<dl>
<dt>Auction Ending:</dt>
<dd><?php
if(!function_exists('countdown')) {
function countdown($year, $month, $day, $hour, $minute) {
$the_countdown_date = mktime($hour, $minute, 0, $month, $day, $year, -1);
$current = time();
$difference = $the_countdown_date - $current;
if ($difference < 0) $difference = 0;
$days = floor($difference/60/60/24);
$hours = floor(($difference - $days*60*60*24)/60/60);
$minutes = floor(($difference - $days*60*60*24 - $hours*60*60)/60);
echo $days."d ".$hours."h ".$minutes."m";
}
}
$theyear = date("Y",strtotime($row_RSproperty['propEndDate']));
$themonth = date("n",strtotime($row_RSproperty['propEndDate']));
$theday = date("d",strtotime($row_RSproperty['propEndDate']));
$thehour = date("H",strtotime($row_RSproperty['propEndDate']));
$theminute = date("i",strtotime($row_RSproperty['propEndDate']));
countdown($theyear,$themonth,$theday,$thehour,$theminute);
?></dd>
<?php if ($row_RSproperty['propCurrBid'] > 0) { ?>
<dt>Current bid:</dt>
<dd>£<?php echo number_format($row_RSproperty['propCurrBid']); ?></dd>
<?php } else { ?>
<dt>Starting Price:</dt>
<dd>£<?php echo number_format($row_RSproperty['propStartPrice']); ?></dd>
<?php } ?>
<dt>Buy it now:</dt>
<dd><span class="green">£<?php echo number_format($row_RSproperty['propBinPrice']); ?></span></dd>
</dl>
</div>
</div>
</div>
<?php
} while ($row_RSproperty = mysql_fetch_array($RSproperty));
/*while ($min <= $max) {
$page .= '<li>'.$min.'</li>';
$min++;
}*/
$page .= ob_get_contents();
ob_end_clean();
$page .= '</div>';
// return the JSON
echo json_encode(array( 'pagination' => $pagination, 'page' => $page, 'current' => $loadPage ));
exit;
?>
Many thanks
Chris
That's because you have hard coded LIMIT as 0 in your query
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, $limit";
So when you move on second page, the query must be getting generated like follow
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, 4";
hence you re getting first 4 records. If you want to retrieve the next set of records on subsequent pages, then you have to make 0 in LIMIT 0, $limit dynamic like:
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT $offset, $limit";
You have to calculate $offset depending on how much results you are displaying per page. On first page, offset will always be 0. If you are displaying 10 records per page, then on second page, offset will be 11, on third offset will be 21 and so on.

Categories