i want to use jquery datepicker to pick a date then when select it to do select query from the database according to the selected date
i've seek about that and found this question
jQuery datepicker with php and mysql
they say i should use ajax to do it
but i can't understand the implementation they do!
can anybody help please
i try to do something like that
<script>
$(function() {
$( "#datepicker" ).datepicker({minDate: 0, showAnim: "bounce",
onSelect: function(dateText, inst) {<?php mysql_select_db($database_conn, $conn);
$query_time = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date='"?>dateText<?php "'" ;
$time = mysql_query($query_time, $conn) or die(mysql_error());</script>
Change your JS to send an ajax call in the onSelect, passing the dateText.
$( "#datepicker" ).datepicker({
minDate: 0,
showAnim: "bounce",
onSelect: function(dateText, inst) {
$.ajax({
type: 'POST',
url: 'select_time.php',
data: {date : dateText},
success: function(resp){
if(false !== resp){
alert(resp);
}
}
});
}
});
Then in select_time.php
<?php
if(!empty($_POST['date'])):
$mysqli = new mysqli('connection info'); //mysqli connection
$stmt= $mysqli->prepare('SELECT reservation.R_time FROM reservation WHERE reservation.R_date = ?'); //prepare the statement
$stmt->bind_param('s', $_POST['date']); //bind our parameters
$stmt->execute(); //execute our query
$stmt->store_result(); // store result so we can check rows
$stmt->bind_result($resTime); //we only want the reserveration time
$stmt->fetch(); //fetch the rows
if($stmt->num_rows() > 0):
echo $resTime; //return the time from the database
$stmt->close(); //close the statement
else:
return false; //row doesn't exist, return false
endif;
endif;
?>
This is untested, but I don't see any reason why it shouldn't work.
I think you're confusing a couple of things:
First, the PHP will always run before the page is loaded (and therefor the jQuery), so calling the PHP on the jQuery selector will never work.
What you need to do is create an ajax function that will fire on the jQuery's onSelect (and I generally use the onClose event if it is a popup calendar).
Javascript:
$( "#datepicker" ).datepicker({
minDate: 0,
showAnim: "bounce",
onClose: function(dateText, inst) {
$.post('select_time.php?dateText=' + dateText, function(queryResult){
// do something with the return query
});
}
});
PHP page:
$connection = mysqli_connect("localhost","username","password","db");
$sql = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date={$_post['dateText']}";
if ($result = mysqli_query($connection , $sql))
{
while ($getData = mysqli_fetch_field($result))
{
echo $getData->R_time;
}
mysqli_free_result($result);
}
mysqli_close($connection);
Related
This question already has answers here:
jQuery UI Datepicker onchange event issue
(19 answers)
Closed 5 years ago.
I have this code in default.php:
jQuery(document).ready(function() {
jQuery(function($) {
var $from = jQuery("#from"),
$to = jQuery("#to");
$from.datepicker({
numberOfMonths: 1,
minDate: 1,
dateFormat: 'dd-mm-yy',
onClose: function(selectedDate) {
$to.datepicker("option", "minDate", selectedDate);
}
});
$from.change(function() {
jQuery.ajax({
url: 'index.php?option=com_vehiclemanager&task=default2',
type: 'POST',
data: {
datepicker_value: $(this).val()
},
success: function(data) {
$('#result').html(data);
}
});
});
...
This is the php script:
<?php
$database = JFactory::getDBO();
$datepicker_value = isset($_POST['datepicker_value']) ? $_POST['datepicker_value'] : NULL;
$month = date("m",strtotime($datepicker_value));
$selectstring = "SELECT * FROM #__vehiclemanager_rent_sal WHERE fk_vehiclesid = 128 AND monthW = '$month'";
$database->setQuery($selectstring);
$string = $database->loadObject();
header('Content-Type: application/json');
$array[] = array(
'deposito'=>$string->deposit,
'spese'=>$string->cfee,
);
echo json_encode($array);
?>
I have a jquery datepicker in a table and i want to pick the variable from the php script via a database query with an ajax call, i can see the json object [{"deposito":"300","spese":"100"}]
but the single php variabile shows me undefined.
I inserted the task in the ajax url because the filename sends me back to the index.php, the homepage, as this is an external plugin.
I hope I explained myself and thanks for your help.
Instead of $(this).val(), try referencing the actual element. Something like this: $('#from').val().
As a follow up to Display image as background in fullcalendar, I now have a fully working MySQL solution, but I cannot find a way to change the background if a custom column that I set in my database is not empty (picture), nor changing the same opacity according to the same condition.
In my other question, I was able to change the background in dayRender and the opacity in eventRender:
dayRender: function (date, cell) {
cell.css("background","url(https://www.mozilla.org/media/img/firefox/firefox-256.e2c1fc556816.jpg) no-repeat center");
cell.css("background-size","contain")
},
eventRender: function(event, element) {
$(element).css("opacity", "0.75");
}
});
Now my js code looks like this:
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
events: "/events.php",
dayRender: function (date, cell, view) {
cell.css("background","url(https://www.mozilla.org/media/img/firefox/firefox-256.e2c1fc556816.jpg) no-repeat center");
cell.css("background-size","contain")
},
eventRender: function(event, element) {
}
});
})
The PHP page to get the event data from the MySQL database is:
<?php
// List of events
$json = array();
// Query that retrieves events
$requete = "SELECT * FROM evenement ORDER BY id";
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=HIDDEN', 'HIDDEN', 'HIDDEN');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
I tried to use this in dayRender to change the background with no success so far:
var eventoObj = $("#calendar").fullCalendar( 'clientEvents')[0];
alert(eventoObj.picture_url)
Can anyone help me out figuring this out?
Thank you for your time and help.
Hi i developed all this functionality using core PHP everything is working well. Now the main thing is i want this one in CodeIgniter so i am trying to shift the core PHP code into CI code.
My aim is in a view page of codeIgniter there will be two date fields called start date and end date. On the page load which will contain current dates in both fields. These two date fields will be used to select a date range. Those two dates will be shown using below code in the view page called view.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#start_date" ).datepicker({
defaultDate: "+1w",
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#end_date" ).datepicker( "option", "minDate", selectedDate );
}
}).datepicker("setDate", "0");
$( "#end_date" ).datepicker({
defaultDate: "+1w",
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#start_date" ).datepicker( "option", "maxDate", selectedDate );
}
}).datepicker("setDate", "0");
});
</script>
</head>
<body>
<div id="main">
<div id="dates">
<label for="start_date">start date:</label>
<input type="text" id="start_date" name="start_date" />
<label for="end_date">end date:</label>
<input type="text" id="end_date" name="end_date" />
</div>
</div>
</body>
</html>
Now this view page will be called from this below controller called show.php.
<?php if(! defined('BASEPATH') ) exit("NO Direct Script Access Allowed");
class Show extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('view_model');
}
public function view()
{
$this->load->view('view');
}
}
Now we can see two date fields in the view page in a proper CI configurations.I can see up to this. Now i want to send these two date fields to query something in the database, get those and show it in the drop down using Ajax call. So i tried to do it in the following way.
$(document).ready(function(){
var from_date = $("#start_date").val();
var to_date = $("#end_date").val();
$.ajax({
type: 'POST',
async: false,
url: '<?php echo base_url().'show/get_ros';?>',
data : { from: from_date , to: to_date },
success : function(res){
$('#ro').html(res);
}
});
});
The above function is added in the view file and another div tag will be added in the view file to show the results form this Ajax call.
<div id="result">
<select name="ro" id="ro">
</select>
</div>
But before i implement something in model side i am checking whether post call is coming to controller method get_ros or not but it's not coming. I am in middle without knowing how to proceed any one helps it will be great.
First thing first you need to make a new function in your controller which will recieve the data from the ajax call
<?php
public function get_ros(){
if($this->input->post(null)){
//print_r($this->input->post());die; #just to check if the values alerted in the success function of the ajax call or else commnet this line.
echo $result = $this->your_model->your_function(); #call the model function to return the result in HTML markup or whatever
}else{
echo '0'; #if no post submission is found just echo 0
}
}
?>
In your model you will get the post variables:
<?php
function your_function(){
### dump the post variables into local variables ###
$from = $this->input->post('from_date', true);
$to = $this->input->post('to_date', true);
#query your database as you like and "return " the data
}
?>
few things,
add an errorHandler to your ajax request like
error:function(XMLHttpRequest,textStatus,errorThrown){console.log('status: '+textStatus+'error: '+errorThrown}});
so you can see the response status in your console, if there ain´t no error, log your response
I´m not too much into php but doesn´´t javascript think that " show/get_ros" is a js-variable ?
so it must be
url: '<?php echo base_url()."show/get_ros";?>',
and i´m not too much into ajax calls but mustn the data option be an object or String ? so rather
data : "from="+from_date+"&to="+to_date ,
Try to use double quotes " inside the single quote in the ajax url
url: '<?php echo base_url()."show/get_ros";?>',
OR
url: '<?php echo site_url("show/get_ros");?>',
Hope it makes sense
Also you should wrap the ajax call on focus out of the second date fields
$(document).ready(function(){
$("#end_date").focusout(function(){
var from_date = $("#start_date").val();
var to_date = $("#end_date").val();
$.ajax({
type: 'POST',
async: false,
url: '<?php echo base_url()."show/get_ros";?>',
data : { from: from_date , to: to_date },
success : function(res){
$('#ro').html(res);
}
});
});
});
this is my PHP code_
if(isset($_REQUEST['show']))
{
$con=mysqli_connect("localhost","root","","server_name");
$show = mysqli_query($con, "SELECT * FROM name1 ORDER BY date DESC");
$html='';
while($showE = mysqli_fetch_array($show))
{
$html.= '<h3>'.$showE['un_name'].'</h3>';
$html.= '<div>'.$showE['un_name_dec'].'</div>';
}
echo $html;
//End of while loop
}
this is jquery code_
$.post('preprocessor.php', '&show=', function(data) {
$("#accordion").html(data);
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
});
this is body_
<div id='accordion'>
</div>
i am not getting real time updates, everything is working, but the Ajax thing is not working... it works if i refresh or reload the page but not itself
What you are looking for is setTimeout.
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
setInterval(makePostCall, 15000); // decide interval to fetch new updates. 15 sec for example
function makePostCall(){
$.post('preprocessor.php', '&show=', function(data) {
$("#accordion").html(data);
});
}
But this is not the proper way of doing this kind of stuff. Consider using Ajax Push Engine
it works if i refresh or reload the page but not itself
For this you need to use setInterval(); function which will check every specific time period which is given:
setInterval(function(){
$.post('preprocessor.php', '&show=', function(data) {
$("#accordion").html(data);
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
});
},5000); //<---- runs every 5000 ms
This will run every 5 seconds and will update the #accordion div.
try:
$.post('preprocessor.php', {show:''}, function(data) {
$("#accordion").html(data);
$("#accordion").accordion({
collapsible: true,
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
}
});
},'html');
Are you setting interval to call the code in certain intervals? All you need to do is,
on JavaScript add:
setinterval(function(){/* do the post here */ },1000 /*this is time */);
I've been working on this for a couple of hours and it should work but i'm missing something!
basically, i'm using jquery autocomplete with json source, with 2 values id and description.
Description should show up in suggestions and if item is selected and ID passed to a hidden field ( the field is not hidden currently for testing purposes)
here's my code:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php",
minLength: 3,
formatItem: function(data, i, n, value) {
return value.split("|")[1];
}
});
$("#CurrentProv").result(function(event, data, formatted) {
if (data)
$("input#fid").val(data[0]);
});
});
//PHP valid json output
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'].'|'.$row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
I've searched and done various variations and still doesn't work!!! My brain is shutting down!!!!!!!!
First, switch to using the actual jQuery UI autocomplete.
You'll have to sort out how to format your items on the server side, or in your JSON callback, because formatItems is not supported anymore. Check out this guide for some help.
Now that you've done that, here's how it will look:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.value);//or ui.item.desc perhaps
}
});
});
Working tweaked PHP code and JS as Ryley suggested:
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'];
$searchArray['id'] = $row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.id);//or ui.item.desc perhaps
}
});