I have a list of dates stored in a MYSQL table, the idea is if the following field has valued 'completed' the row's date is unselectable in the jQueryUI datepicker. The dates are stored in the format YYYY-MM-DD.. how would I go about loading these 'completed' dates into a PHP array in a format for the datepicker to understand and disable them? JSON would be the obvious answer, I've spent the last couple of weeks getting to grips with it. Any example code of the jquery / php code would be greatly appreciated.
Many thanks in advance.
[ I have done research around the subject but it is not particularly well documented.. I've already got the datepicker showing valid days in a week. The jqueryUI datepicker seems to be able to do everything except make me a cup of tea. ]
EDIT: So I've managed to feed the array of dates with 'final' status through with JSON, I thought i'd provide the code if it helps anyone:
<?php
//connect to local db
include('functions.php');
connectLocal($localcon);
//locate rows with status set to final
$result = mysql_query("SELECT sendDate FROM my_table WHERE status='final'");
// return corresponding dates as json array
$i=0;
while($row = mysql_fetch_array($result))
{
$confirmedSends[$i] = array ( "sendDate" => $row['sendDate']);
$i++;
}
header('Content-type: application/json');
$jsonConfirmedSends = json_encode($confirmedSends);
echo $jsonConfirmedSends;
?>
This can retrieved with json in the form of a list of dates. The alert box pops up once for each date. About to get to work on presenting these to my datepicker array.
$.getJSON("get-disabled-dates.php",
function(data){
$.each(data, function(index, completed) {
alert(completed.sendDate);
});
});
Try following code to match your situation which disables set of dates. You can get dates by using json from your mysql table using $.getJSON of jquery
$(function() {
$( "#pickdate" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: checkAvailability
});
})
var $myBadDates = new Array("10 October 2010","21 October 2010","12 November 2010");
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
source : http://codingforums.com/showthread.php?t=206879
Related
I have a form in yii2. In that I have a input field like below.
<input type="text" class="form-control" id="productsales-<?= $i ?>-value">
It's inside a dynamic form andno coming from any model.It's just to hold some calculated value. And the idea is to calculate the values fileed by users in this field to another textbox like below -
<?= $form->field($model, 'amount')->textInput(['maxlength' => true, 'class' => 'sum']) ?>
I already have the javascript code to calculate the total amount like below -
<?php
/* start getting the total amount */
$script = <<<EOD
var getSum = function() {
var items = $(".item");
var sum = 0;
items.each(function (index, elem) {
var priceValue = $(elem).find(".sumPart").val();
//Check if priceValue is numeric or something like that
sum = (parseFloat(sum) + parseFloat(priceValue)).toFixed(2);
});
//Assign the sum value to the field
$(".sum").val(sum);
};
//Bind new elements to support the function too
$(".container-items").on("change", ".sumPart", function() {
getSum();
});
EOD;
$this->registerJs($script);
/*end getting the total amount */
?>
Please note that I have a class sum in the second textbox which comes from a model. My question is that how can I add a class(sumPart) like this(sum) in the first textbox which is not coming from a model.
Update after discussion with Insane Skull
I have a dynamic form like below
I want to calculate sum of all the entries in Value and pass it to amount.
The code of Value is -
<input type="text" class="form-control sumPart" id="productsales-<?= $i ?>-value">
The code of Amount is -
<?= $form->field($model, 'amount')->textInput(['maxlength' => true, 'class' => 'sum']) ?>
The javascript I've tried is already given above.
The problem with this code is the calculated "value" is not passing to amount textbox.
Update: A little issue
Modify JS :
$this->registerJs('
function getSum() {
var sum = 0;
var items = $(".item");
items.each(function (index, elem) {
var priceValue = $(elem).find(".sumPart").val();
sum = parseFloat(sum) + parseFloat(priceValue);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
$(".sum").val(sum);
}
$(".container-items").on("change", function() {
getSum();
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
I am little unsure about the problem you are facing. If you want to add a class to a input field, you can easily do so in the class attribute of the input tag. And the class attribute does support multiple values, so you can write something like this:
<input type="text" class="form-control sumPart" id="productsales-<?= $i ?>-value">
**UPDATE -- based on comment by OP **
#Tanmay, I understand that you may not be getting the desired output. However, it should not really matter if we are rendering the fields using $form->field() or plain HTML. If the fields have the proper classes assigned, then the JS code posted by Kostas in your referenced link should work - irrespective of how the class name was added to the input field.
Can you please confirm (by using Inspect Element) if the sumPart class is actually assigned to the relevant fields once the page loads? Maybe some JS is overwriting the class attribute again?
If the classes are assigned properly, please check if there are any other JS errors in console which may prevent the sum calculation JS from working properly.
sorry for disturbing...I got json format to build column highcharts that will accept data from user multiple selected via checkbox and retrieve the data result from database based on what they check at checkbox and display by highcharts in form of column chart..
The problem is,I think my json format for column highcharts is not correct can anyone see my code and tell me what wrong with this....below this is the json output and the code..:- Thank u very much for your time..
Let say if I checked 2 checkbox from the checkboxes list (BAT123 & BIO22), this json will displayed like this:
[{"name":"Subject","data":["BAT123"]},{"name":"Result","data":[3.03]}]
[{"name":"Subject","data":["BAT123","BIO222"]},{"name":"Result","data":[3.03,1.05]}]
I know that json format is wrong, I tried to fixed it but still failed..I am a newbie..hope u can try to fix my code below.
Here is the json code:
<?php
if(isset($_GET['iddoc'])) //iddoc is the value from selected checkbox
{
$category = array();
$category['name'] = 'Subject';
$series1 = array();
$series1['name'] = 'Result';
foreach ($_GET['iddoc'] as $iddoc)
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($r = mysql_fetch_assoc($sql_query))
{
$category['data'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
$jsonTable = json_encode($result, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
}
?>
well I know it's easier on html5, but I have to use html4 or xhtml and I can't find any info without html5 somehow. Can anyone help and explain me how I can input a date?
<input type="text" name ="sometext">
The normal html4 or xhtml doesn't seem to have the type date as the type of input.
Thanks in advance.
This question has been asked & answered on some other StackOverflow threads, but as I'm hitting the same problem, here's more info.
Using the jQuery DatePicker is a good start, but it does not enforce format or min/max value integrity outside of the actual calendar popup. Meaning, you can type or paste some bad stuff.
Here's 2 links to sites that demo how to do it the "old way" in JS with a function:
http://www.javascriptkit.com/script/script2/validatedate.shtml
http://www.w3resource.com/javascript/form/javascript-date-validation.php
And here's a StackOverflow link to another pretty nice way to do it:
Detecting an "invalid date" Date instance in JavaScript
Personally, I need validation and restriction to min and max date ranges (SQL hates dates before 1/1/1773 and somebody tried that in my app). I'm going to wire up a function that tells me if a date string is valid, and then wire that up to the input's onchange event.
Here's the HTML for mine:
I'm also using ASP.NET and jQuery's DatePicker, so the key element for folks is the onblur event.
Here's the JS for the FixValidDate() function:
var availableDateFormats = ["mmddyyyy","mm/dd/yyyy","mm-dd-yyyy","yyyy/mm/dd","yyyy-mm-dd"];
function FixValidDate(txtDate,nulls, minDate, maxDate) {
//debugger;
formats =
{
'mmddyyyy':{
're':/^(\d{1,2})(\d{1,2})(\d{4})$/,
'month': 1,'day': 2, year: 3
},
'mm/dd/yyyy':{
're':/^(\d{1,2})[/](\d{1,2})[/](\d{4})$/,
'month': 1,'day': 2, year: 3
},
'mm-dd-yyyy':{
're':/^(\d{1,2})[-](\d{1,2})[-](\d{4})$/,
'month': 1,'day': 2, year: 3
},
'yyyy/mm/dd':{
're':/^(\d{4})[/](\d{1,2})[/](\d{1,2})$/,
'month': 2,'day': 3, year: 1
},
'yyyy-mm-dd':{
're':/^(\d{4})[-](\d{1,2})[-](\d{1,2})$/,
'month': 2,'day': 3, year: 1
}
}
dateText = txtDate.value;
matched = false;
for(i=0; i<availableDateFormats.length; i++)
{
f = formats[availableDateFormats[i]];
match = dateText.match(f.re);
if(match)
{
matched = true;
month = match[f.month];
day = match[f.day];
year = match[f.year];
//TODO validate if the numbers make sense
txtDate.value = month+"/"+day+"/"+year;
}
}
if (!matched && nulls) {
txtDate.value = "";
return false;
} else {
var timestamp = Date.parse(txtDate.value);
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
if (minDate != null) {
if (d < minDate) {
txtDate.value = "";
return false;
}
}
if (maxDate != null) {
if (d > maxDate) {
txtDate.value = "";
return false;
}
}
} else {
txtDate.value = "";
return false;
}
}
return true;
}
This is from an old library I've used for JS stuff for about a decade. You could easily find another JS validation function and swap mine out.
In my function, I required to accept a variety of date formats, and if it's a bad format, I blank out the field and keep the user in the same box. You could change that up.
HTML4 doesn't have any tags to input date by default.All you need to do is include third party library like JQUERY.
Checkout this example http://jqueryui.com/datepicker/
The basic input element is all that HTML (other than HTML5) has. You should have a label, with associated markup, for all text input. Normally you should also include information about the expected input format, as this varies by language and culture, e.g.
<label for="birth">Date of birth (day/month year):</label>
<input id="birth" type="text" name="birth" size="10">
You should also pre-check the user input client-side, with JavaScript, to give the user fast response in case of data error. Naturally, the checks should be duplicated server-side.
Hmmm, maybe someone can help me out here or point me in the right direction , as i have been banging my head against the wall for a number of days now and dont seem to be gettin anywhere useful.
(and admittedly i'm pretty new with regards to json,objects, google visulization etc)
essentially, i am running 3 different queries on the same page against 3 different fusion tables, which in return are supposed to return an array of 3 different xets of markers.
all is fine, when i run the queries individually and make an array of the markers .
however, running the 3 queries on the same page, i can't seem to find a way to identify the query in the response function.
any hints much appreciated. and i'll be happy to provide more info if needed (tried to get rid of some unneccessary stuff)
this is what i have. thanks
a) calling the function "setFusionData()" with all relevant vars. something like setFusionData("'LatLng','name'", 2729461);
(this is calles 3 times with different variables)
function setFusionData(selColumns,tableId) {
/****
an actual query example is this:
http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
****/
var query = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq='+ encodeURIComponent("SELECT "+selColumns+" FROM "+tableId+"")
);
query.send(getFusionData); //do something with the response
}
function getFusionData(response) {
/**
here, is the problem as i need to get the table id or reqId or anything that is uniquely passed on from "setFusionData" above
also something like
alert(JSON.stringify(response)) does not return any reqId or table id either
***/
/*return rows/columns and add values to an array of markers***/
var numRows = response.getDataTable().getNumberOfRows();
var numCols = response.getDataTable().getNumberOfColumns();
for (i = 0; i < numRows; i++) {
/* add markers to array etc this works fine***/
}
}
i also tried something like this:
function setFusionData(selColumns,tableId) {
......
query.send(getFusionData({reqId:tableId}));
}
function getFusionData(response) {
alert(response['reqId']);//returns tableId. but how do i get the tableData ?
}
with wich i can get the reqId, but not the table*Data*. So I am only able to get either id or data :(
----edit----------------
after messing around a bit more (see below) it appears that the key/value pairs that get returned when typing the query into the browser directly are different than what gets returned by the call from the script...i.e the following
http ://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
typed directly into the browser bar will return
version:'0.5',reqId:'1234',status:'ok',table etc
however, calling the same from within the script returns something like
{
"rj":"0.5","ef":"ok","pb":[],"qb":[],"h":"{"cols":
[{"id":"col2","label":"LatLng","type":"string"},{"id":"col1","label":"name","type":"string"}],
"rows":
[{"c":[{"v":"47.20572,12.70414"},
{"v":"Hohe Tauern"}]},{"c":[{"v":"47.5530395,12.925611"},{"v":"Berchtesgaden"}]},{"c":[{"v":"47.5585405,14.61887"},{"v":"Gesu00e4use"}]}],
"p":{"totalrows":3}
}"
}
, so no 'reqId' but only some cryptic keys (without one that looks like the reqId either)...... anyone any idea why that would/could be ?
Sometimes you can figure it out by just looking at the JSON response, your sample request returns:
google.visualization.Query.setResponse({
version:'0.5',
reqId:'1234',
status:'ok',
table: {
...
}
})
You already got response.reqId to identify which request is this the response for, now you can use response.table to create a new DataTable instance:
var dt = new google.visualization.DataTable(response.table);
Or, since you have multiple tables, put then in an array indexed with the reqId
tables[response.reqId] = new google.visualization.DataTable(response.table);
You'd do var tables = new Array() before calling setFusionData() for the first time.
Thank-you to all who have helped me over the last few days.. Unfortunately I was working so I couldn't get back to you. I have included some code into what I thought would work, but for some reason the below code will not update in my SQL Database. I will provide the code and it's output if someone could please copy the code and see why it's not working... It's really doing my head in! Haha!
(The connection to the MySQL db + table is working fine).
// admin.php
<a href="#" id="chngeHref" /><img src="<?php echo "image.php?url=" . $row[2]; ?>?tid=<?php echo $row[0]; ?>&opn=<?php echo $row[1]; ?>" id="chnge" /></a>
// image.php?url=image.jpg?tid=3&opn=1
I was advised to do it this way to make it easier for me to pass the variables (tid and opn) through the process.
// update.php
$tid = $_GET['tid'];
$opn = $_GET['opn'];
if ($opn == "0") { $opn = "1"; } elseif ($opn == "1") { $opn = "0"; }
mysql_query("UPDATE catalogue SET opn = $opn WHERE tid = $tid ; ");
mysql_close();
// it's just a simple script to change a variable from 1 to 0 or 0 to 1 where tid = a specific number...
I have my jQuery stuff all tucked away in a lovely little file, because there is alot of it...
// navigate.js
$.extend({
getUrlVars: function() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
return vars;
}
});
$("#chngeHref").click(function() {
var tid = $.getUrlVars()['tid'];
var opn = $.getUrlVars()['opn'];
$.ajax({
type: "POST",
url: "update.php",
data: "tid="+ tid +"& opn="+ opn,
success: function(){
$('#chnge').fadeTo('slow',0.4);
}
});
});
The .extend code i found on the net which finds the parameter and value of all those in the address line. I THINK this is where my issue might be, because the top code is never actually sending it to the address bar, it's being sent through jQuery to the update.php file.
I can only say thank-you soooo much in advance to anyone who can assist in this.
Phillip.
There are a few issues here bsides the SQL Injection vulnerability Nathan mentions, namely you're POSTing, so you need to use $_POST rather than $_GET to retrieve your variables. Also you have an extra space in the data block, this:
data: "tid="+ tid +"& opn="+ opn,
should be:
data: "tid="+ tid +"&opn="+ opn,
or a bit cleaner using object notation (so it also gets properly encoded):
data { tid: tid, opn: opn },
For the SQL Injection issue, instead of this:
mysql_query("UPDATE catalogue SET opn = $opn WHERE tid = $tid ; ");
At the very least escape the values, like this:
$tid = mysql_real_escape_string($_POST['tid']);
$opn = mysql_real_escape_string($_POST['opn']);
Or, go the parameterized query route, which is what I'd prefer.