how to connect jquery datepicker to table of data? - php

I have code to display a table, mysql queries fetching data from a database. One of the columns is dates. I would like to use the jquery datepicker to sort the table. I've included the correct files and show the calendar on my site but how do I connect it to my table so I can sort my data?
<form name="myForm" action="/page.php" onsubmit="return validateForm()" method="get">
<input type="text" id="from" name="fromDate" value=""/>
<input type="text" id="to" name="toDate" value=""/>
<input type="submit" name="Find Dates" value="Submit" />
</form>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#from').datepicker({
defaultDate: "+1w",
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
jQuery('#to').datepicker({
defaultDate: "+1w",
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
</script>
<?php
$values = $wpdb->get_results($wpdb->prepare( "SELECT DISTINCT DATE FROM `signup` ORDER BY DATE ASC"));
?>
<table>
<tr>
<th>Date</th><th>B</th><th>D</th>
</tr>
<tr>
<?php
foreach($values as $v_date){
$date = $v_date->DATE;
$count = $wpdb->get_results($wpdb->prepare(
" SELECT DISTINCT `date`,
(select count FROM signup where LIST_NAME = 'B' AND date = '$date') as 'B',
(select count FROM signup where LIST_NAME = '2 - D' AND date = '$date' ) as 'D', FROM wp_email_signup WHERE date ='$date'"));
echo '<tr class="row_main">';
echo '<td>' . $date . '</td>';
foreach($count as $counts){
$val1 = $counts->B;
$val2 = $counts->D;
echo '<td>' . $val1 . '</td>';
echo '<td>' . $val2 . '</td>';
echo '</tr>';
}
?>
</tr>
</table>

You can get value from datepicker like this:
<script>
jQuery('#from').click(function(){
//this is the value of datepicker
var datepickerVal = $(this).val();
//here you you have to pass this value to php
window.document.location = '?from =' + datepickerVal;
})
</script>
After that after page reload you can get this value in php from $_GET array and use it as you want

You could call a different PHP file in jQuery using AJAX. In that PHP file you query anything you want to the database, and echo the results in a JSON syntax. This way, you can parse it from Javascript and show it on the datepicker :)
References:
jQuery AJAX: http://api.jquery.com/jquery.ajax/
Encode a PHP array to JSON: http://php.net/manual/es/function.json-encode.php

Whoa, take it easy. You should not mix all the code into one file. You should separate database code, php code, javascript and css code as much as possible. You should have a code which runs the search with the necessary parameters and retrieves the data. You should post the parameters using ajax when the date value has been changed. Here you can see an example of posting with ajax.

Related

jQuery UI slider won't allow me to pass its current value to the URL

I am currently working on this site for a client and I today hit a brick wall when I found I was unable to pass the current value from a jQuery slider to the URL in order to filter results from an SQL query.
Judging from the interface on the site it should be pretty clear what I want to accomplish, a user should be able to select what type of product they want to purchase, this currently refreshes the page and passes the value to the url when the button is pressed.
<form name="pumpType" action="<?php echo $_SERVER['PHP_SELF']; ?>?s=<?php echo $pType ?>&p=<?php echo $pVal ?>&g=<?php echo $gVal ?>" method="get" align="center">
<div class="btn-group" data-toggle="buttons-radio">
<button type="submit" class="<?php if( $pType == 'intermittent' ){ echo 'active '; } ?>btn btn-primary waitingUiBut" id="but1" name="s" value="intermittent">INTERMITTENT</button>
<button type="submit" class="<?php if( $pType == 'continuous' ){ echo 'active '; } ?>btn btn-primary waitingUiBut" id="but4" name="s" value="continuous">CONTINUOUS</button>
</div>
</form>
My client wants the user to be able to further refine the query results once the category has been filtered, I chose to use sliders to accomplish this.
When the sliders value changes I want my SQL query to run, constantly refining the result set ( I assume I will have to use AJAX to do this? Correct me if I am wrong ). The problem I am having is that only the ?s= variable is ever sent to the URL, both ?p and ?g variables do not get recognised.
SQL Query -
$pType = $_GET['s'];
$pVal = $_GET['p'];
$gVal = $_GET['g'];
$sql = "SELECT * FROM pumps
WHERE pump_type='$pType'
AND flow_psi <= '$pVal'
AND flow_gpm <= '$gVal'
AND high_psi <= '$pVal'
AND high_gpm <= '$gVal'";
jQuery Ui Slider Markup -
<div align="center" class="productSlider">
<form name="pumpSlider" action="?s=<?php echo $pType ?>&p=<?php echo $pVal ?>&g=<?php echo $gVal ?>" method="get">
<p class="inlineLabel">PSI</p><div class="filterSlider" id="psiSlider" name="p" value="1000"></div>
<p class="inlineLabel">GPM</p><div class="filterSlider" id="gpmSlider" name="g" value="1000"></div>
</form>
</div>
jQuery slider submission code ( to eventually be handled by AJAX )
$(document).ready(function() {
$("#psiSlider" ).slider({
// options
start: function (event, ui) {
},
slide: function( event, ui ) {
var curValue = ui.value || initialValue;
var target = ui.handle || $('.ui-slider-handle');
var tooltip = '<div class="tooltip"><div class="tooltip-inner">' + curValue + '</div><div class="tooltip-arrow"></div></div>';
$(target).html(tooltip);
},
change: function(event, ui) {
$('#pumpSlider').submit();
}
});
$("#gpmSlider" ).slider({
// options
start: function (event, ui) {
},
slide: function( event, ui ) {
var curValue = ui.value || initialValue;
var target = ui.handle || $('.ui-slider-handle');
var tooltip = '<div class="tooltip"><div class="tooltip-inner">' + curValue + '</div><div class="tooltip-arrow"></div></div>';
$(target).html(tooltip);
},
change: function(event, ui) {
$('#pumpSlider').submit();
}
});
});
Why are my p and g variables not being captured on the form submission? Any suggestions would be most appreciated.
Your problem is that your 'p' and 'g' are both in div tags, and div tags do not have a value attribute. You can use input fields and make them hidden so that you can have values for these.
<p class="inlineLabel">PSI</p><div class="filterSlider" id="psiSlider"></div>
<p class="inlineLabel">GPM</p><div class="filterSlider" id="gpmSlider"></div>
<input type="hidden" name="p" value="1000" />
<input type="hidden" name="g" value="1000" />
Then when you are moving the slider, make sure it is using/replacing the values of the input instead of trying to use a value on the div.

JQuery Auto-Complete: How do I handle modifications?

I have auto-complete working, but how do I handle modifications?
What happens when the user modifies the original selection? I've got an auto-complete that, when a listing is chosen, other fields are filled in. If the user chooses a listing, then tries to modify it to something that is new (does not match anything in our DB), the other fields need to be cleared.
Another way of asking: How do I handle 'new' listings?
My code below
$(function() {
$( "#oName" ).autocomplete({
source: "include/organizerList.php",
minLength: 3,
select: function( event, ui ) {
$("input#oID").val(ui.item.oID);
$("input#oCID").val(ui.item.oCID);
$("div#organCity").text(ui.item.oCity);
$("div#organCountry").text(ui.item.oCountry);
}
});
});
organizerList.php
// important to set header with charset
header('Content-Type: text/html; charset=utf-8');
$term = htmlspecialchars(strtolower($_GET["term"]));
$return = array();
$query = mssql_query("SELECT CID, oID, oName, oCity, oCountry FROM TradeShowDB_Organizers WHERE oName LIKE '%$term%'");
while ($row = mssql_fetch_array($query)) {
array_push($return,array( 'oCID'=>$row['CID'], 'oID'=>$row['oID'], 'label'=>$row['oName'] . ', ' . $row['oCity'], 'value'=>$row['oName'], 'oCity'=>$row['oCity'], 'oCountry'=>$row['oCountry'] ));
}
// encode it to json format
echo(json_encode($return));
My html:
<input type="text" tabindex='20' id="oName" name="oName" size="60" maxlength="200" value="<?php echo $oName; ?>">
<div id='organCity'></div>
<div id='organCountry'></div>
<input type="hidden" id="oID" name="oID" value="<?php echo $oID; ?>">
<input type="hidden" id="oCID" name="oCID" value="<?php echo $oCID; ?>">
You can use the autocomplete select event http://jqueryui.com/demos/autocomplete/#event-select
Disable the input once the user selects an option
$("#oName").autocomplete({
source: "include/organizerList.php",
minLength: 3,
select: function (event, ui) {
this.value = ui.item.value;
$('#autocomplete').autocomplete("disable");
$('#autocomplete').trigger('keypress'); //needed to fix bug with enter on chrome and IE
$(this).attr('disabled','disabled');
return false;
},
autoFocus: true
});
http://jsfiddle.net/HKxua/6/
Then in your server side script, you can check the input to see if the value posted exists in the database.

How to insert ID from Jquery UI auto complete

i make a jquery autocomplete and its data come from mysql database.now i m facing a small problem in this.
i want to show product name in autocomplete as u see in code below & its working good.but after clicking submit button i want to insert product ID instead of product NAME.Below is my code
<?php
require_once "include/config.php";
$sql_product = "select * from tbl_product";
$res_product = mysql_query($sql_product);
?>
<script>
$(function() {
var availableTags = [
<?php
while($rs_product = mysql_fetch_array($res_product))
{
$prod_name = $rs_product['prod_name'];
?>
"<?php echo $prod_name; ?>" <?php echo ", "; ?>
<?php
}
?>
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
<label for="tags">Tags: </label>
<input id="tags" />
You can pass in your values to availableTags source in format like:
[{label:"Prod Name 1", value:1}, {label:"Prod Name2", value:2}]
Create a hidden input element, like
<input type="hidden" name="hidAutoComplete" value="" />
And:
$( "#tags" ).autocomplete({
source: availableTags,
select: function(event, ui) {
var selectedObj = ui.item;
$(this).val(selectedObj.label);
$('input[name="hidAutoComplete"]').val(selectedObj.value);
return false;
}
});
Hope it helps
TRY ( I assume there is prod_id column in your table )
var availableTags = [
<?php
while($rs_product = mysql_fetch_array($res_product))
{
$prod_id[] = $rs_product['prod_id'];
}
echo json_encode($prod_id);
?>
];
update
use json_encode

How do you calculate total cost with input fields using jQuery?

I've been searching online for a solution to my problem but no luck yet. I'm hoping someone will be able to get me past this obstacle I've hit or point me in the right direction.
I'm creating an online registration form for players. So far, when I select a birth date using jquery's datepicker, it will return the correct age of the user based on the specific date I've set. I'm using a switch statement to display the correct division name and price value on the webpage based on the age selected.
All seems to work correctly up to this point.
My problem now is that I cannot seem to target the value of each price in order to create a function that adds up each price for a grand total.
HTML portion taken from my php file:
<div>
<div>
<label for="player-birthdate-1">Birthdate</label>
<input type="text" class="default-input" id="datepicker1" value="">
</div>
<div>
<label for="player-division-1">Division</label>
<input type="text" id="playerDivision1" value="" disabled>
</div>
<div>
<p id="playerFee1" class="fee" value=""></p>
</div>
</div>
<div>
<div>
<label for="player-birthdate-2">Birthdate</label>
<input type="text" class="default-input" id="datepicker2" value="">
</div>
<div>
<label for="player-division-2">Division</label>
<input type="text" id="playerDivision2" value="" disabled>
</div>
<div>
<p id="playerFee2" class="fee" value=""></p>
</div>
</div>
<div>
<p id="total" value=""></p>
</div>
Portion taken from my php file where I'm grabbing the division name and price from the database:
<script>
var divisions = {
<?php
$sql = $db->prepare("SELECT * FROM division");
$sql->execute();
$results = $sql->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $division) :
?>
'<?php echo $division->division_id; ?>' : {
id : '<?php echo $division->division_id;?>'
,name : '<?php echo $division->division_name;?>'
,price : '<?php echo $division->division_price;?>'
},
<?php endforeach; ?>
}
</script>
Datepicker and Total Fee code taken from my js file:
$(document).ready(function() {
$( '#datepicker1' ).datepicker({
onSelect: function(value, ui) {
var newDate = new Date("April 30, " + (new Date()).getFullYear()),
dob = $("#datepicker1").datepicker("getDate"),
age = new Date(newDate - dob).getFullYear() - 1970;
$('#age').val(age);
console.log(age);
switch (age){
case 5:
case 6:
$("#playerDivision1").val(divisions['1'].name);
$("#playerFee1").html(divisions['1'].price);
break;
case 7:
case 8:
$("#playerDivision1").val(divisions['2'].name);
$("#playerFee1").html(divisions['2'].price);
break;
//continues on for the remaining of the ages.....
},
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: '1990:2012'
});
$( '#datepicker2' ).datepicker({
onSelect: function(value, ui) {
var newDate = new Date("April 30, " + (new Date()).getFullYear()),
dob = $("#datepicker1").datepicker("getDate"),
age = new Date(newDate - dob).getFullYear() - 1970;
$('#age').val(age);
console.log(age);
switch (age){
case 5:
case 6:
$("#playerDivision2").val(divisions['1'].name);
$("#playerFee2").html(divisions['1'].price);
break;
case 7:
case 8:
$("#playerDivision2").val(divisions['2'].name);
$("#playerFee2").html(divisions['2'].price);
break;
//continues on for the remaining of the ages.....
},
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: '1990:2012'
});
$('.fee').html(function(){
var total = 0;
$('.fee').each(function(){
var fee = parseFloat($(this).val());
if (isNaN(fee)) {fee = 0;}
total+= fee;
$('#total').html('$' + total);
});
});
});
I look forward to advice from those on the forum. Any help or push in the right direction is greatly appreciated! :)
You've done a nice job and made it easy by giving each one a class of "fee" already, but I assume you want to parseFloat the number, not parseInt (in case there's cents in the fee?).
Also, you need to check if it's isNaN (not a number), otherwise it won't work properly.
That's a simple matter of adding:
if (isNaN(fee)) {fee = 0;}
Finally, it appears that you're doing it on the "change" event. I've had better luck with the keyup event.
I think what's happening is the line (and it's code):
$('.fee').html(function(){
is never actually being called or it's not being called at the right time.
My suggestion would be to wrap the contents of the .fee stuff in a function. Then call that function in the date picker's select callback. (Probably right before every break; statement.) This way the total would be recalculated every time the date changes.
Your function would look something like this:
function calcFee () {
var total = 0;
$('.fee').each(function () {
...
});
}
If you are doing the calculations inside the jQuery each() function loop then you can use the jQuery $(this).val() to grab the value inside each box. Then you can create a cumulative total.

mysql dateformat with jquery date format not working out

I have a mypage.php and it contains the below code
And i have added the
<link style="text/css" href="http://jqueryui.com/themes/base/jquery.ui.all.css" rel="stylesheet">
<script type="text/javascript" src="/scripts/jquery.js"></script>
<script type="text/javascript" src="/scripts/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="/scripts/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/scripts/ui/jquery.ui.datepicker.js"></script>
<form name="test_date" method="post">
<input type="text" id="datepicker1" name="date1">
<input type="submit" name="insert" value="Insert and show">
</form>
And In jquery.ui.datepicker.js i have change the date format to dateFormat: 'dd/mm/yy' from dateFormat: 'mm/dd/yy'
and below is the jquery for selecting the date when click on textbox
<script>
$(function() {
$( "#datepicker1" ).datepicker();
});
</script>
And when i click on submit button i have inserted into mysql database database
<?php
if($_POST['insert']) {
echo "Date : ";
$d = $_POST['date1'];
require('con_open.php');
$t = date('Y-m-j H:i:s', strtotime($d));
mysql_query("insert into date_table (date_field1) values ('$t')");
echo "Converted to Date at Runtime :" . $t;
echo "<br>";
$query = mysql_query("select date_field1 from date_table");
while($r = mysql_fetch_row($query))
{
got_date_db = $r[0];
}
echo "Displaying date from Database : " . got_date_db;
require('con_close.php');
}
?>
Output :
Converted to Date at Runtime : 2011-12-28 14:32:16
Displaying date from Database : 0000-00-00 00:00:00
date_field1 (DATETIME) fromat on mysql
Even i have tried out checking with dateformat of mysql and php date function manuals online and over stackoverflow... but i could not get any solution to this one.
Try:
mysql_query("
insert into date_table (date_field1)
values (FROM_UNIXTIME(". (int)strtotime($_POST['date1']) ."))
");
I think its generally a good idea to pass a date as a timestamp to the database. Then you don't have to worry about formatting it the right way.

Categories