I'm trying to create a validation for an "", but I can't understand how to.
The form has two dates:
DateStart
Datestop (must be after Datestart).
These variables are stored as associative array (routine['col'] =>'val').
I created this:
<form ..>
...
<tr>
<td>Star date: </td>
<td><input type="date" name="routine[Datestart]"></td>
</tr><?php $routine['Datestart']; ?>
<tr>
<td>Stop Date: </td>
<td><input type="date" name="routine[Datestop]"
min="routine[Datestart]"></td>
</tr>
...
</form>
Obviously, the min option doesn't work.
I saw that some solution are provided by Javascripts, but I never used Java, so if I could do it with a simple php variable it would be better, but I'm looking for the smartest solution, so I ask to you simply how to do that.
Validitions on the web are done in two places:
On the server (PHP). You always need to check user input on your server before inserting data from the wild webs into your database. The simplest possible validation to check that a field is not blank would be:
<?php
$errors = array();
if ( empty($POST["foo"]) || count($POST["foo"]) < 1) {
$errors["foo"] = "Foo can't be blank";
}
if ( empty($errors) ) {
// all good here
} else {
// display errors to user.
}
This is a pretty trivial example and great volumes have been written on different ways to validate user input.
To compare two dates in PHP you need to parse the input string into a two DateTime objects which you then can compare:
$start = DateTime::createFromFormat(DateTime::RFC3339, $routine['Datestart']);
$end = DateTime::createFromFormat(DateTime::RFC3339, $routine['Dateend']);
if ($start > $end) {
// its not valid.
}
In the browser. Since server side validions require the user to press send before getting feedback which is pretty slow at times they are often complemented with client side validations which give instant feedback while the user types. The are written in Javascript [not to be confused with Java] since it is the universal language of the browser.
However they are never a replacement for client side validations as a script error or the user not having javascript enabled would disable the validations.
you should use jquery like this.
jquery code
<script type="text/javascript">
$(function () {
$("#DateFrom").datepicker(
{
dateFormat: "dd-mm-yy",
changeMonth: true,
changeYear: true,
yearRange: '-50:+50',
maxDate: 'today',
onSelect: function (selectedDate) {
$("#DateTo").datepicker("option", "minDate", selectedDate);
}
}
);
$("#DateTo").datepicker(
{
dateFormat: "dd-mm-yy",
changeMonth: true,
changeYear: true,
yearRange: '-50:+50',
maxDate: 'today',
onSelect: function (selectedDate) {
$("#DateFrom").datepicker("option", "maxDate", selectedDate);
}
}
);
});
</script>
HTHML CODE OR JUST INCLUDE IT IN UR FORM
<center>
<input type="text" id="DateFrom"> To
<input type="text" id="DateTo">
</center>
you have to include jquery datepicker js and css. files.
try this one it will works.
Related
How can I update mysql fields without refreshing the page, from a list of results from the database.
Using datepicker
In a single .php page?
Example:
order_report.php
$query = $this->db->query("select order_id,
date_format(date_payed,'%d-%m-%Y') as date_payed,
from oc_order");
***code left out to save space***
foreach ($res as $orders) {
print $orders['order_id'];
<input type="text" name="datepicker" id="datepicker" value="<?php echo $orders['date_payed']; ?>"/>
$query = $this->db->query("update oc_order SET date_payed='$datepicker' WHERE order_id='$orders['order_id'];'");
}
Jquery
<script>
$(document).ready(function() {
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd'
});
})
</script>
I'm assuming what you are asking is that you want the datepicker to update your MySQL table when you select on a date without having to refresh that page. The code you provided is a little confusing, but I put something together that may help.
I am guessing that the input field that's in your code is actually supposed to be the html where you are getting the value.
As for keeping it all on one single page... I don't think that will be possible. For best results, you will have to make a new .php page to accept the value of the datepicker, which is passed through the $.ajax call where it says date. If you did it on the same page, there's a possibility you may end up getting a swamp of unwanted html data returned to you via the data parameter in the success function, but it would most likely throw an error and get the error function callback.
In this example, I called the php page process_date.php.
HTML:
<input type="text" id="datepicker" value="<?php echo $orders['date_payed']; ?>"/>
JS:
<script type="text/javascript">
$(document).ready(function () {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function () {
var date = $("#datepicker").val();
$.ajax({
type: "POST", //or GET. Whichever floats your boat.
url: "path/to/process_page.php",
data: { date: date },
success: function(data) {
alert(data);
//Write code here for you successful update (if you want to)
},
error: function() {
alert("Error.");
}
});
}
});
});
</script>
PHP (process_date.php)
<?php
$date = $_POST['date']; //if you used GET in your ajax, then use $_GET here instead
$query = $this->db->query("select * from oc_order");
***code left out to save space***
foreach ($products as $orders) {
print $orders['order_id'];
$query = $this->db->query("update oc_order SET date_payed='$date' WHERE order_id='$orders['order_id'];'");
echo "Success";
}
?>
Note: Not saying you didn't, but don't forget to always sanitize your PHP data before sending it to the server in order to avoid being attacked via SQL Injection. Even if you use parameterized queries, it is still a good idea.
As the title says, how can i test/show my jQuery variable in php? I have created a datepicker and on the click of a specific date, that date needs to be stored into a variable so i can use it later on (like for example to show your date of birth).
The code of the datepicker and the Onselect is:
$(document).ready(function(){
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
alert(dateText);
document.getElementById('thedate').value=dateText;
},
showOn: "button",
buttonImage: "/debasis/hoofdstuk03/img/calendar.png",
buttonText: "Open de kalender",
buttonImageOnly: true,
inline: true,
showOtherMonths: true,
dayNamesMin: ['Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za','Zo'],
monthNames: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni',
'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
});
});
The HTML to show the datepicker is:
<div type="text" id="datepicker"></div>
<form method=post>
<input type='text' id='thedate' name='thedate' />
</form>
If im right, but correct me if i am wrong, when i click a date on the calendar, that date is being POST and the Jquery variable 'thedate' will be set in $_POST['thedate'] is this correct?
However to be sure i got the chosen date in my $_POST (so i can use this variable to store it in my databse) i wanted to test it with an echo. So in the same file i created this to test it:
<?php print_r($_POST); ?>
Though this little line doesnt return anything? Anyone knows how i can test/show 'thedate' variable (the chosen date)? So i know the chosen date is stored in a variable. I would like to get it returned in a PHP variable so i can store it in my databse.. Though if there are other ways to do it i am open for those solutions as well. :)
AJAX post it to an external php file. $_SESSION the var in that file and use it wherever else.
nope; it doesn't work like that. It's not enough to just change input value. You need to actually submit the form - which means comunicating with php which is BACK-END, to be able to show it using PHP.
the easiest way would be to submit the form in onSelect method:
HTML:
JS:
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
alert(dateText);
document.getElementById('thedate').value=dateText;
document.getElementById("myForm").submit();
},
...
and then print it out usign PHP:
<?php print_r($_POST); ?>
How to make work datepicker according to server time , how to set the server time to datepicker Jquery Ui, any help will be appreciated
Yes via clinet side we cannot get the server datetime, is there any procedure to get the server date/time and apply to date picker in PHP?
<?php $_date=date("d-m-Y"); ?>
<input type="text" class="datepicker" name="_date" value="<?=$_date;?>"/>
hope this will help.
//In my case i have used folloing script. Hope it will help you!
$('#selectedPicker').datepick
({
yearRange: '1980:2010',
alignment: 'bottomRight',
onSelect: updateSelected,
altField: '#set_Date',
showTrigger: '#calImg'
}).datepick('setDate', '<?php echo $server_date; ?>');
Use this. It will work and set maxDate if possible so the greater date is not selected
$(function() {
$( "#ppcertdate" ).datepicker({ maxDate: "<?=date("d/m/Y");?>", dateFormat: 'dd/mm/yy' });
$("#ppcertdate").datepicker("option","defaultDate", "<?=date("d/m/Y");?>");
});
Okay, that's a presumptuous title - it's complex to me.
Overview: (See screenshots and UPDATE at bottom.)
a. On $(document).ready, jQuery/AJAX builds table with one contact per row
b. Each table row, 3rd cell, is: <a id="edit_83">edit</a> tag -- "83" is example and represents the contact_id from db, so each a tag will have a unique id number that is used in step (d)
c. As table being built, construct jqueryui dialog (autoOpen=false) for each contact in AJAX callback
d. when any edit anchor is clicked, jquery splits off the contact_id and uses that to display the appropriate jQueryUI dialog.
Objective: Clicking on edit link in any table row opens a jqueryui dialog with edit form for that contact.
Problem: The form opens, but there are no form fields inside. In fact, in the DOM the injected form/div is missing for each table row. ???
HTML:
<div id="contact_table"></div>
Javascript/jQuery - AJAX call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ax_all_ajax_fns.php",
data: 'request=index_list_contacts_for_client&user_id=' + user_id,
success: function(data) {
$('#contact_table').html(data);
var tbl = $('#injected_table_of_contacts');
tbl.find("div").each(function() {
$(this).dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons:
{
Okay: function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
})
});
}
});
});
AJAX/PHP 1 - ax_all_ajax_fns.php:
}else if ($_POST['request'] == 'index_list_contacts_for_client') {
$user_id = $_POST['user_id'];
$r = build_contact_table_for_client($user_id);
echo $r;
}
AJAX/PHP 2: - functions.php
function build_contact_table_for_client($user_id) {
$aContact_info = get_contact_data_ARRAY_user_id($user_id, 'first_name','last_name','email1','cell_phone', 'contact_id');
$r = '<table id="injected_table_of_contacts">
<tr>
<th width="120">Name</th>
<th width="200">Email Address</th>
<th width="100">Cell Phone</th>
<th>Action</th>
</tr>
';
while ($rrow = mysql_fetch_array($aContact_info)) {
$r .= '
<tr>
<td>'.$rrow['first_name'].' '.$rrow['last_name'].'</td>
<td>'.$rrow['email1'].'</td>
<td>'.$rrow['cell_phone'].'</td>
<td>
<a class="editcontact" id="edit_'.$rrow['contact_id'].'" href="#">edit</a>
/
<a class="delcontact" id="del_'.$rrow['contact_id'].'" href="#">del</a>
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<form name="editForm" onsubmit="return false;">
<p class="instructions">Edit contact information:</p>
First Name:<span style="padding:0 20px;">Last Name:</span><br />
<input type="hidden" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'">
<input type="hidden" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'">
Email:<span style="padding:0 20px;">Cell Phone:</span><br />
<input type="hidden" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'">
<input type="hidden" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'">
</form>
</div>
</td>
</tr>
';
}
$r .= '</table>';
return $r;
}
jQuery - document.click event - if injected code missing, how is it able to find the selector??
$(document).on('click', '.editcontact', function(event) {
var contact_id = this.id.split( 'edit_' )[1];
var etc = $( '#editThisContact_' + contact_id );
etc.dialog("open");
});
UPDATE - PARTIAL SOLUTION:
The dialog is now appearing - the cancel button was out of place, per this post. However, the injected code has vanished. Nothing else changed - just got the dialog code working by fixing syntax error in placement of cancel button.
In response to the question on my comment on the original post:
You really already know JSON, it stands for JavaScript Object Notation. This is a JSON object:
{"a":1,"b":2,"c":3}
look familiar? JSON is just a fancy name for something we've been using a long time (that may not be 100% true, but it's how I see it.)
The idea is to have the server pass back JSON objects and have your JavaScript create/update HTML based on them. In your scenario, you were having your PHP build multiple HTML dialogs. Instead, you would have your PHP pass back an array of objects each one representing a single row from your table, like so:
{
"records":
[
{
"field a":"value a",
"field b":"value b"
},
// record 2
{
"field a":"value a",
"field b":"value b"
}
]
}
If you were to request that from the server using .getJSON(), jQuery would automatically read that and give you a an object with a .records property that is an array of objects! Now you can use JavaScript to update a single dialog/form on the screen when they click one of the corresponding records.
Note: You could have PHP just pass back an array of objects, but it is best practice to wrap it in an object above. Many times you'll want other info too, for example, when you are doing paginated search results you're going to need to know the total number of records and what page you're on and maybe other data points.
An added benefit of this is that the server is done much faster. You push all of the display logic onto the client's computer, and hence, can server more pages from the same server.
That's a real brief explanation. There are tutorials and examples ALL OVER the web. Any good Ajax app you use online (GMail for example) uses JSON objects instead of passing huge blocks of HTML around. Here are a few links, Google has quite a few more:
http://php.net/manual/en/function.json-encode.php (turn any variable into a JSON string.)
http://www.json.org/example.html
http://www.w3schools.com/json/default.asp
http://www.jsonexample.com/
PHP Example: http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Another PHP Example: http://www.jquery4u.com/json/ajaxjquery-getjson-simple/ (the alternative method for json-data.php in this link is the way to go, the other way is just silly!)
There are also some really good frameworks out there to help out with this process. I'm a huge fan of both backbone.js and spine.js. Both use jQuery, both help you use best practices when building apps (like MVC.)
It's nice when you solve your own question. Not so nice when the answer is a ID-ten-T error.
In the injected HTML, note the type of the input fields (screenshot 1). Change type to type="text", and all works as desired.
When concepts are new, Occam's Razor moves almost beyond reach.
I still don't understand why I can't see the injected markup, though..!
I have asked this before, but my meaning was not understtod...
My Situation is that I need the Start and End JQuery datepicker on the webpage, and it must... #1 - The End Date must always be greater then Start Date... #2 - The date range must POST data from MySQL to create a table of the data on the webpage.
How can I change the script below (that has #1 working of the tasks needed above), to also POST the information from MySQL via PHP back to the HTML DIV.
See the example of what I am building on my webpage here
1.<script type="text/javascript">
$(function () {
var start1 = $('#start1');
var end1 = $('#end1');
start1.datepicker({ onClose: clearEndDate });
end1.datepicker({ beforeShow: setMinDateForEndDate });
function setMinDateForEndDate() {
var d = start1.datepicker('getDate');
if (d) return { minDate: d }
}
function clearEndDate(dateText, inst) {
end1.val('');
}
})
There was another jQuery function on your site that you didn't include:
$('#button').click(function() {
$.post('report.php', {
start: $('#start1').val(),
end: $('#end1').val()
},
function(data) {
$('#genreport').html(data).show();
});
});
You probably already know this, but you will also need to reformat and filter/verify the date inputs in your report.php page. I hope this helps. I didn't realize this question was so old until I just posted it. HAH! Just ignore this, as you probably have it working already.