I have a JQuery calendar plugin I'm using currently and as of right now I'm stuck on trying to figure out how to populate the calendar with information from a PHP file using AJAX.
var Script = function () {
// calendar
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
/*---------------------------------------------------------------------------*/
window.onload = function myfunction() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("calendar").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../ajax/calendar.php", true);
xmlhttp.send();
}
/*---------------------------------------------------------------------------*/
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: false,
events: [
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
]
});
}();
This is the PHP File
<?
$query = mysql_query("SELECT * FROM table WHERE id = '1093'");
do {
$message = $row['message'];
$hour = $row['hour'];
$minute = $row['minute'];
$year = $row['year'];
$month = $row['month'];
$day = $row['day'];
$status = $row['status'];
if(eregi('pending', $status)) {
echo '
{<br>
title: '.$message.',<br>
start: new Date('.$year.', '.$month.', '.$day.', 12, 0),<br>
end: new Date('.$year.', '.$month.', '.$day.', 14, 0),<br>
allDay: false<br>
},
';
}
}while($row = mysql_fetch_array($query));
} else header('location: error.php');
?>
How do I get the info from my database table to loop into my JQuery plugin?
PHP have a json_encode() method allowing you to convert PHP arrays to valid JSON objects.
Also make sure to output the correct content-type header.
header('Content-Type: application/json');
echo json_encode($my_datas_from_DB);
Just output your content with this method so it can be consumed by JavaScript.
(Side note: JSON is not HTML, <br> wouldn't be valid here as you try to output JSON manually)
It's much easier than you think, you can define your events property as an ajax call like so (right in your fullcalendar initialization):
...
events: {
url: '../phpPath/pathToEventScript.php',
dataType: 'json',
type: "POST"
},
...
just be sure that each event object (in your array of objects) has a start property.
PHP script:
$select = "SELECT title, start FROM events";
$stmt = $db->query($select);
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($events);
Do something like this:
"your.js" could be something like this:
$.get( "../ajax/calendar.php", function( data ) {
$('#calendar').fullCalendar(eval("(" + data + ")"))
alert( "Calendar initilazed ;)" );
});
and your php file havenot to include "< br >" tag as new line!
Related
I'm working with Ajax for the first time and I'm trying to translate an ajax request from javascript to jquery and can't figure out how to do it.
Here is my javascript code:
function aaa(track_id) {
var req = new XMLHttpRequest();
req.open("get", "list.php?tr=" + track_id, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.onreadystatechange = bbb;
req.send();
}
function bbb(e) {
if(e.target.readyState == 4 && e.target.status == 200) {
antwort = e.target.responseXML;
document.getElementById("title").firstChild.nodeValue = antwort.getElementsByTagName("ti")[0].firstChild.nodeValue;
document.getElementById("artist").firstChild.nodeValue = antwort.getElementsByTagName("art")[0].firstChild.nodeValue;
}
};
And here is the list.php:
<?php
header("Content-Type: text/xml; charset=utf-8");
$con = mysqli_connect("", "root", "", "music");
$res = mysqli_query($con, "SELECT * FROM tracks WHERE track_id = " . $_GET["tr"]);
$dset = mysqli_fetch_assoc($res);
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<data>";
echo " <tr>" . $dset["track_id"] . "</tr>";
echo " <ti>" . $dset["title"] . "</ti>";
echo " <art>" . $dset["artist"] . "</art>";
echo "</data>";
?>
Can anyone help me? Thanks in advance!
Whilst the other answers will "do the job", there are some refinements you can make.
jQuery has a specific get method which simplifies things, and in addition, you can put the data into an object passed to the get or ajax call instead of appending it to the url as in other answers:
function aaa(track_id) {
$.get( 'list.php',
{ tr: track_id },
function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
}
);
}
Another improvement is to structure it as a Promise:
function aaa(track_id) {
$.get( 'list.php',
{ tr: track_id }
).done( function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
});
}
The advantage of this is that you can chain error handling onto this relatively easily.
Turning to list.php, there are a few problems with it.
It would probably be better returning JSON instead of XML, as that would reduce the complexity of the success code, but obviously you can't do things like that if other applications expect an XML API.
<?php
// protect against MySQL injection by using parameters...
$query = '
SELECT track_id AS tr, title as ti, artist as art
FROM tracks
WHERE track_id=?';
$mysqli = new mysqli("", "root", "", "music");
// this needs more error checking...
$stmt = $mysqli->prepare( $query);
$stmt->bind_param( 's', $_GET['tr']);
$stmt->execute();
$result = $stmt->get_result();
$dset = $result->fetch_assoc();
// simpler to return JSON
header('Content-Type: application/json');
echo json_encode( $dset);
?>
jQuery.ajax() method is used to perform an AJAX (asynchronous HTTP) request.
function aaa(track_id) {
$.ajax({
url: "list.php?tr=" + track_id,
dataType: "json",
success: function (result) {
bbb(result);
}
});
}
function bbb(e) {
antwort = e;
document.getElementById("title").firstChild.nodeValue = antwort.getElementsByTagName("ti")[0].firstChild.nodeValue;
document.getElementById("artist").firstChild.nodeValue = antwort.getElementsByTagName("art")[0].firstChild.nodeValue;
};
The equivalent of making an AJAX in jQuery is $.ajax(). You can also put the XML in the response in to a jQuery object and traverse that to find the values you require. Given the logic you've shown, you could implement it like this:
function aaa(track_id) {
$.ajax({
url: 'list.php',
data: { tr: track_id },
success: function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
}
});
}
This is assuming that the firstChild of the targeted elements is a textNode.
I have a couple of FullCalendar instances each in its own Tab.
At first when I switched tabs, the calendars did not display, so I added this part to render the calendars once you click on a tab
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var redrawcal = $(this).attr('href');
redrawcal = redrawcal.substring(1,redrawcal.length);
$('#calendar_'+redrawcal).fullCalendar('render');
$('.fc-today').removeClass('fc-today');
});
This works perfectly for each tab after the first, however, the first Tab's calendar's event times are incorrect.
As shown in the image below, the second tab's events are correct:
But The first tab does not rerender the events correct, the initial placement and the placement if you switch tabs are exactly the same, as seen in the image below:
I have the following code that's suppose to render the calendar after it has been created at first:
$(function(){
//first tab's calander is not rendering correctly, this will make it show correct from the start
<?php $branch = $branches[0]; ?>
<?php $branch_studio_id = str_replace(" ", "_", $branch['branch_studio_name']); ?>
<?php $branch_studio_id = preg_replace("/[^a-zA-Z]/", "", $branch_studio_id); ?>
$('#calendar_<?= $branch_studio_id; ?>').fullCalendar('render');
});
For this example, the calendar's id is calendar_Centurion, the PHP simply removes spaces and special characters
I have also tried this:
$('#calendar_<?= $branch_studio_id; ?>').fullCalendar('rerenderEvents');
But I still have the same results.
The two events in the two calendars have exactly the same times on the same day, and all information is the same
If there is only one Tab, it is broken without an extra tab to rerender the calendar.
I have basically tries everything that I could find and that I could think of that might help but with no positive results.
Unfortunately I cannot create a fiddle of this as it would take quite long to do so and the actual code/project is not open to the public as of yet.
I do hope this can be easily solved.
Thanx in advance!
UPDATE
Below is the HTML and JS code for my calendars
<?php $branch_studio_id = str_replace(" ", "_", trim($branch['branch_studio_name'])); ?>
<?php $branch_studio_id = preg_replace("/[^a-zA-Z]/", "", $branch_studio_id); ?>
<div class="tab-pane <?=($x == 1) ? 'active' : '' ?>" id="<?=$branch_studio_id ?>">
<div class="row">
<div class="col-md-9">
<div id="calendar_<?= $branch_studio_id ?>"></div>
</div>
<div class="col-md-3">
<p class="h4 text-light">Classes not on timetable</p>
<hr />
<div id='external-events_<?=$branch_studio_id ?>'>
<?php foreach ($classes_notimetable as $class) :?>
<?php if ($class['studio_id'] == $branch['studio_id']) : ?>
<div class="external-event label label-success" data-event-class="fc-event-success" data-class-id="<?=$class['id']?>"><?=$class['class_name'] ?></div>
<?php endif;?>
<?php endforeach;?>
<hr />
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function($) {
'use strict';
var initCalendarDragNDrop<?=$x;?> = function() {
$('#external-events_<?=$branch_studio_id ?> div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject<?=$x;?> = {
title : $.trim($(this).text()), // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject<?=$x;?>);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex : 999,
revert : true,
revertDuration:0
});
});
};
var initCalendar<?=$x;?> = function() {
var $calendar<?=$x;?> = $('#calendar_<?=$branch_studio_id ?>');
var date = new Date();
var daynum = date.getDay();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$calendar<?=$x;?>.fullCalendar({
header: {left: '', center: '', right: ''},
defaultView: 'agendaWeek',
timeFormat: 'HH:mm',
slotDuration: '00:10:00',
snapDuration: '00:05:00',
firstDay : 1,
columnFormat: 'ddd',
minTime:'<?= (isset($school_custom['school_from_hour'])) ? $school_custom['school_from_hour'] : '08'; ?>:<?= (isset($school_custom['school_from_minutes'])) ? $school_custom['school_from_minutes'] : '00'; ?>',
maxTime: '<?= (isset($school_custom['school_to_hour'])) ? $school_custom['school_to_hour'] : '21'; ?>:<?= (isset($school_custom['school_to_minutes'])) ? $school_custom['school_to_minutes'] : '00'; ?>',
allDaySlot: false,
defaultTimedEventDuration: '01:00:00',
forceEventDuration:true,
editable : true,
eventDrop: function(event) {
var eventid = event.id;
var eventday = (event.start._d).getDay();
var eventstarthour = (event.start._d).getHours()-2;
var eventstartminute = (event.start._d).getMinutes();
var eventendhour = (event.end._d).getHours()-2;
var eventendminute = (event.end._d).getMinutes();
$('').postJsonCheck('classes/update_class_times', {event_id: eventid, event_day:eventday, event_starthour:eventstarthour,event_startminute:eventstartminute,event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
},
droppable : true, // this allows things to be dropped onto the calendar !!!
drop : function(date) {// this function is called when something is dropped
var $externalEvent = $(this);
// retrieve the dropped element's stored Event Object
var originalEventObject = $externalEvent.data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
//copiedEventObject.allDay = allDay;
copiedEventObject.className = $externalEvent.attr('data-event-class');
var classid = parseInt($(this).attr('data-class-id'));
copiedEventObject.id = classid;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar_<?=$branch_studio_id ?>').fullCalendar('renderEvent', copiedEventObject, true);
//Update DB
var eventday = (copiedEventObject.start._d).getDay();
var eventstarthour = (copiedEventObject.start._d).getHours()-2;
var eventstartminute = (copiedEventObject.start._d).getMinutes();
var eventendhour = (copiedEventObject.start._d).getHours()-1;
var eventendminute = (copiedEventObject.start._d).getMinutes();
$('').postJsonCheck('classes/add_class_timetable', {class_id: classid, event_day:eventday, event_starthour:eventstarthour,event_startminute:eventstartminute,event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
//remove the event from the not on timbetable list
$(this).remove();
},
eventResize: function(event, delta, revertFunc) {
var classid = event.id;
var eventendhour = (event.end._d).getHours()-2;
var eventendminute = (event.end._d).getMinutes();
$('').postJsonCheck('classes/update_class_duration', {class_id: classid, event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
},
events : [<?php $z = 0;?>
<?php foreach ($classes as $class): ?>
<?php $z++;?>
<?php if ($class['studio_id'] == $branch['studio_id']) : ?>
{
id: <?=$class["day_id"]?>,
title: '<?=$class["class_name"]?>',
start: new Date(y, m, d-(daynum-<?=$class["day"]?>), '<?=$class["start_hour"]?>', '<?=$class["start_minute"]?>'),
end: new Date(y, m, d-(daynum-<?=$class["day"]?>), '<?=$class["end_hour"]?>', '<?=$class["end_minute"]?>')
}
<?php if ($z < count($classes))echo ","?>
<?php endif;?>
<?php endforeach; ?>]
});
};
$(function() {
initCalendar<?=$x;?>();
initCalendarDragNDrop<?=$x;?>();
});
}).apply($(this), [jQuery]);
</script>
*Please note that there is a php foreach loop outside of the above code, so this code gets duplicated for each calendar, each with a unique $branch_studio_id used in the calendar's ID
I am trying to get the server show the client's date and time, but that is not showing the correct output. Here is the relevant part of the code:
<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toString()
$.post(window.location, {
dateStr: dateStr
});
alert(dateStr);
});
</script>
<div id="divMessage">
<?php
$dstr = 'nothing!';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
$dstr = $_POST["dateStr"];
$v = 'current date/time is '.$dstr;
echo "<span style=\"color:green\">$v</span>";
?>
</div>
If the code is correct, I should see "current date time is <client's date/time>", but instead I see "current date time is nothing!". What mistake am I doing here?
Hope this helps, there were several things you needed to add to make it work.
Checking if the page was submitted via post and then parsing the response for the message to redisplay it.
<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toString();
$.post(window.location, {
dateStr: dateStr
}).success(function(data){
var res = $(data).filter('#divMessage').text();
//console.log(res);
$('#divMessage').replaceWith(res);
});
});
</script>
<div id="divMessage">
<?php
//include "simple_html_dom.php";
//$html = new simple_html_dom();
//$html->load_file('index2.php');
//$v = $html->find('div[id=box]', 0)->plaintext;
if (!empty($_POST['dateStr'])) {
$dstr = 'nothing!';
if (isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0) {
$dstr = $_POST["dateStr"];
}
$v2 = 'current date/time is ' . $dstr;
echo "<span style=\"color:green\">$v2</span>";
}
?>
</div>
As other said your have to use 2 file one with the js and other for php, in file.php you can make what you want for example to save in db. I tried to comment the code if you don't understand something feel free to ask.
check the path where you save the file php
file.php
<?php
$result = Array();
if (isset($_POST['action'])) {
$client_date = new Date();
// HERE YOU CAN USE FOR SAVE IN DB
$result ['result_msg'] = 'success';
$result ['client_date'] = $client_date;
} else {
$result ['result_msg'] = 'error';
}
echo json_encode($result);
?>
html
$(document).ready(function(){
$.ajax({
type: "POST",
url: "file.php",
data: {
action : 'what you want'
// IF YOU WANNA SAVE CLIENT INFORMATION HAVE TO MAKE A FORM AND PASS DATA HERE FOR EXAMPLE CLIENT ID ....
},
dataType: 'json'
}).done (function(result) {
result = JSON.parse(JSON.stringify(result));
if (result.result_msg === 'success') {
console.log(result.client_date); // YOU CAN SHOW IN HTML DIV
} else {
console.log('ERROR');
}
}).fail(function(result) {
console.log('ERROR');
});
});
Cheers!!!
Here is what you're missing, see what's data returned from server :)
<script type="text/javascript">
$(document).ready(function(){
var d = new Date();
var returnFromServer =
var dateStr = d.toString()
$.post(window.location, {
dateStr: dateStr
}).success(function(data){
//this is return from server
alert(data);
});
alert(dateStr);
});
</script>
<div id="divMessage">
<?php
$dstr = 'nothing!';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
$dstr = $_POST["dateStr"];
$v = 'current date/time is '.$dstr;
echo "<span style=\"color:green\">$v</span>";
?>
</div>
Anyways you need to split files up , because I think this will return the whole page, and the span with your color :)
How to fetch data and pass. into form and response customername onkeyup or keydown json and php.
<?php
$conn = new mysqli("localhost", 'root', "", "laravel");
$query = mysqli_query($conn,"select * from customers");
while ($result2=mysqli_fetch_assoc($query)) {
$data[] = $result2['customername'];
}
echo json_encode($data);
?>
Here is HTML code with javascript ajax:-
<div id="demo">
CustomerName: <input type="search" name="customername">
</div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "connection.php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
document.getElementById("demo").innerHTML = arr;
}
</script>
How pass into form and response on keyup or keydown and related suggestions customername should display down. I am new to JSON and javascript and examples sites. Thanks in advance. All suggestions are welcome.
From your code sample
$conn = new mysqli("localhost", 'root', "", "laravel");
$query = mysqli_query($conn,"select * from customers");
$dataForJSON = array()
while($result2=mysqli_fetch_assoc($query)) {
$dataForJSON[] = $result2['customerName'];
}
echo json_encode($dataForJSON);
Use this code to return data from json and this will work fine with JSON.parse(response)
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);