I am trying to embed a data picker calendar in my php site. The code, which came off the shelf from DatePicker, allows to select some pre-highlighted dates, which is good as I have a list in a db table with the dates I need.
However, I have had no success in finding a way to include php within the script, or the other way round.
The original calendar script is as follows:
<script type='text/javascript'>
$(function() {
$("#txtDate").datepicker({dateFormat: 'yy-mm-dd'});
});
$(document).ready(function() {
var SelectedDates = {};
SelectedDates[new Date('02/24/2014')] = new Date('02/24/2014');
SelectedDates[new Date('03/10/2014')] = new Date('03/10/2014');
$('#txtDate').datepicker({
beforeShowDay: function(date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true, "Highlighted", Highlight];
}
else {
return [true, '', ''];
}
}
});
});
</script>
I would like to be able to select a long list of dates to go in
SelectedDates[new Date('03/10/2014')] = new Date('03/10/2014');
so my original idea was to do as follows:
$(document).ready(function() {
var SelectedDates = {};
<?php
$query = "SELECT eventDate FROM database.calendar WHERE tag='R' AND competition='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$eventdate = $row[0];
SelectedDates[new Date('$eventdate')] = new Date('$eventdate');
}
?>
Sadly, this doesn't work (and neither do any of the various attempts to re-add tags within the PHP.
Any idea? Thank you so much for your help!
You have to close your PHP tags to output JavaScript (or use echo as mentioned in a comment):
$(document).ready(function() {
var SelectedDates = {};
<?php
$query = "SELECT eventDate FROM database.calendar WHERE tag='R' AND competition='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$eventdate = $row[0];
?>
SelectedDates[new Date('<?php echo $eventdate; ?>')] = new Date('<?php echo $eventdate; ?>');
<?php
}
?>
});
Although I should mention that what you are trying to do is not really ideal. Do the PHP while loop separately, get that into an array, and json_encode that.
Related
I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
I use Pickadate.js and JQuery Form Plugin. I have date and time pickers seperately. What I want to do is to disable times in timepicker according to value of datepicker. So, I am trying to get the JSON data into picker.set("disable", [ ]);. I can console.log the plain text but it remains aimless.
I tried a lot and have come across these solutions in that question. But I couldn't launch them. (I adapted pickadate functions and classes to pickatime's.)
// Javascript
$(document).ready(function() {
$("input").click(function() {
$(".datepicker").pickadate({
format: 'yyyy-mm-dd',
formatSubmit: 'yyyy-mm-dd',
min: true,
max: false
});
var $input = $(".timepicker").pickatime({
format: 'HH:i',
formatSubmit: 'HH:i',
formatLabel: 'HH:i'
});
$('.datepicker').change(function() {
$('#form').ajaxSubmit({
target: '#check_result',
url: 'check.php',
success: function showResponse(responseText, $form) {
var picker = $input.pickatime('picker');
picker.set("disable", [
console.log(responseText)
]);
}
});
return false;
});
});
});
// PHP (check.php)
<?php
// Database connection done.
$date = mysqli_real_escape_string($con, $_POST['date']);
$match_query = mysqli_query($con, "SELECT * FROM booking WHERE DATE(time) = '$date'");
$disabled_times = array();
if ($result = $match_query) {
while ($row = mysqli_fetch_assoc($result)) {
$disabled_times[] = $row['time'];
}
mysqli_free_result($result);
}
echo implode($disabled_times);
?>
Can you post an example of the json being returned from your php?
According to the docs (http://amsul.ca/pickadate.js/api/#method-get-disable)
your json should be something like this: [2,30], [4,30], [9,0]
If your json is correct, be sure it is not being passed to the timepicker as a string. Try something like:
var json = JSON.parse(responseText);
picker.set("disable", [ json ]);
UPDATE:
I guess with the following code, your json will return properly:
...
$time = explode(',', $row['time']);
$time[0] = (int)$time[0];
$time[1] = (int)$time[1];
$disabled_times[] = $time;
...
echo json_encode($disabled_times);
I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.
I have a calendar on my site that uses javascript/jquery to place events in the calendar. All the events are stored in a MySQL database with the title and Unix timestamp.
My problem is that this method (shown in the code below) only allows one event per day, and creating two rows with the same date, only uses the latter of the two. There are several instances where I need two or more events in one day.
My code:
var CalendarEvent = function (time, title) {
this.time = time;
this.title = title;
}
var allEvents = {
<?php require_once 'ndx/mysql.php';
$events = mysqli_query($con, "SELECT * FROM events");
while($lse = mysqli_fetch_array($events)):
$date = date('Y-m-d', $lse['timestamp']);
$notime = $lse['notime'];
if($notime != 'true'){
$time = date('g:i a', $lse['timestamp']);
}else{
$time = '';
}
$event = addslashes($lse['title']);
?>
'<?php echo $date; ?>': [
new CalendarEvent('<?php echo $time; ?>', '<?php echo $event; ?>')
],
<?php endwhile; ?>
I have input with id aktForm_tiekejas and is jquery autocomplete code:
$('#aktForm_tiekejas').autocomplete({
serviceUrl: '_tiekejas.php',
width: 185,
deferRequestBy: 0,
noCache: true,
onSelect: function(suggestion) {alert('You selected:'+suggestion.value+','+suggestion.data);}
});
_tiekejas.php:
<?php
include("../Setup.php");
$query = ($_GET['query']);
$reply = array();
$reply['query'] = $query;
$reply['suggestions'] = array();
$reply['data'] = array();
$res = mysql_query("SELECT id,pavadinimas FROM sarasas_tiekejas WHERE pavadinimas LIKE '%$query%' ORDER BY pavadinimas ASC");
while ($row = mysql_fetch_array($res)) {
$reply['suggestions'][] = $row['pavadinimas'];
$reply['data'][] = $row['id'];
}
mysql_close();
echo json_encode($reply);
?>
If query is 'vac' php returns from server:
{"query":"vac","suggestions":["UAB Vivacitas"],"data":["866"]}
but
alert('You selected:'+suggestion.value+','+suggestion.data);
doesn't alert data (866)
why?...
Probably because suggestion.value doesn't exist. Looking at your JSON response code I can see the suggestion.data but no suggestion.value. Since JS will be looking for a value that doesn't exist it will throw an error. Also you're missing out the array for the second part of the return. Try this:
alert('You selected: '+suggestion.data[0]);
If you need to iterate through your data subsets do something like:
for(i in suggestion.data){
alert('You selected: '+suggestion.data[i]);
}