I'm using fullcalendar to present events of my site members. Everyone can add own event. Each event have to have unique ID which I'm getting using SELECT INCREMENT(MAX('id')) in PHP. Then proper var is passed to JavaScript and here is a problem. The number is given to the fullcalendar renderEvent function at the second try of adding new event. At first click on calendar, variable is empty as declared (in variable named newEventId).
Here is my code:
function showCalendar() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var newEventId = '';
$('#kalendarz').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
editable: false,
dayClick: function(e)
{
$.getJSON('/ajax/call/bands/AddEvent', function(data) {
newEventId = data.dane;
});
console.log(newEventId); // <- empty, then with ID at second click...
$("#kalendarz").fullCalendar('renderEvent',
{
title: 'Termin zajęty',
start: e,
id: newEventId
});
},
});
}
What is the problem? renderEvent function is not waiting for getJSON to finish job? Could I fix it?
$.getJSON is AJAX, AJAX is asynchronous! Set it inside $.getJSON callback function:
$.getJSON('/ajax/call/bands/AddEvent', function (data) {
newEventId = data.dane;
$("#kalendarz").fullCalendar('renderEvent', {
title: 'Termin zajęty',
start: e,
id: newEventId
});
});
getJson() initiates an AJAX request, which is asynchronous, getJSON returns after initiating the AJAX-request, but that doesn´t mean that the request itself has finished already. Therefore you can hand over a function onSuccess, which will be called with the received data when the request finished.
If the mechanism wouldn´t work this way you weren´t able to do anything while the request is sent - imagine clicking somewhere, that click calls a function and somehow a request is started, then everything would wait until the request would finish: at the highest level you couldn´t even move your mouse anymore until you receive some response data - that isn´t user-friendly at all ;)
Solving your problem is easy by putting all the code after your request which depends on its response inside the onSuccess-function (you have the function already)
Related
I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});
I've set setInterval to update my scheduler. I'm getting data from server in JSON format. But Scheduler is not getting update if I used json data, But if I put static values it works fine. Following is my code.
// It doesn't work
setInterval(function() {
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var startdt=data.processing[i].start_interval.split(",");
var endt=data.processing[i].end_interval.split(",");
var month=parseInt(startdt[1])-1;
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
var section="'"+data.processing[i].section_id+"'";
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: new Date(start),
end_date: new Date(end),
css: "inprocess",
sections: {
unit: section
}
});
scheduler.updateView();
}
Same TimeInterval with static data works fine.
// This works properly.
setInterval(function() {
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var startdt=data.processing[i].start_interval.split(",");
var endt=data.processing[i].end_interval.split(",");
var month=parseInt(startdt[1])-1;
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
var section="'"+data.processing[i].section_id+"'";
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: new Date(2013,11,29,01,00),
end_date: new Date(2013,11,29,01,30),
css: "inprocess",
sections: {
unit: 'a7b6e635-f62f-6f12-020f-52a959d1ca47'
}
});
scheduler.updateView();
}
}
},'json');
}, 5000);
}
},'json');
}, 5000);
If it works with the static data, that means that dynamic data either comes wrong or is parsed wrong on the client.
Make sure that dates and section are correct.
For example, in this code, where you collect a date string from the ajax values and check this string in console:
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
console.log(start);
console.log(end);
It would be more informative if you check the resulting date, that is passed to the scheduler API.
console.log(new Date(start));
console.log(new Date(end));
Date string might have some non-obvious error which results in invalid date object.
Secondly, the code that collects the dates is rather complex. I'd suggest to use a simplier format for transfering dates from the server(for example use unix timestamp), or to define some helper function for parsing them.
FYI, scheduler library includes scheduler.date object that defines methods for working with dates.
So you can define parse function like following. That leaves much less space for typos and accidental errors. Not quite sure that I've specified the correct date format, but you can change it if it's necessary
var parseDate = scheduler.date.str_to_date("%Y, %m, %d, %H, %i");
var start = parseDate(data.processing[i].start_interval),
end = parseDate(data.processing[i].end_interval);
One particularly suspicious line is where you retreive id of the section:
var section="'"+data.processing[i].section_id+"'";
I think you add extra quotes to the section id here. I mean var section will be equal to
"'a7b6e635-f62f-6f12-020f-52a959d1ca47'" , while in your static code you use "a7b6e635-f62f-6f12-020f-52a959d1ca47" - without extra quotes
One more thing. You call scheduler.updateView() each time timespan is added. Since this command triggers complete redraw of the calendar, it's better to call it only once when the loop is finished.
UPDATE:
here is the code sample. Didn't actually run it, but i hope it clarifies the text above
setInterval(function() {
var parseDate = scheduler.date.str_to_date("%Y, %m, %d, %H, %i");// parse string of specified format into date object
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var timespan = data.processing[i];
var start = parseDate(timespan.start_interval),
end = parseDate(timespan.end_interval),
section = timespan.section_id;
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: start,
end_date: end,
css: "inprocess",
sections: {
unit: section
}
});
}
//update calendar after loop is finished
scheduler.updateView();
}
},'json');
}, 5000);
How would I fill in the boxes of my form if I select one of the values from the dropdown menu (The dropdown is got from the DB) Somehow in my javascript I need to connect to functions as there is to different tables involved with the form fields.
Question
Do I need to set the fields using $field name?
if(document.id('LoadExtension') && document.id('ExtensionResponse')) { // id of select box
var sel = document.id('LoadExtension'); // ser select box as var.
sel.addEvent('change', function(chg) { // add change event to select box.
if(sel.getSelected().get('value') != '') { // on change if selected value is not empty.
new Request.HTML({
url : 'http://domain.co.nz/index.php?extension='+ sel.getSelected().get('value'),
onRequest: function() {
},
onComplete: function(r1, r2, html, js) {
document.id('ExtensionResponse').set('html', html);
}
}).send();
}
});
}
The above code was set up to get from another document in the url: box but I would like to do it in one page.
for your code:
http://www.jsfiddle.net/dimitar/TXHYg/4/
(function() {
// anon closure for scope purposes of local vars.
// cache selectors used repeatedly into local vars.
var sel = document.id('LoadExtension'), resp = document.id('ExtensionResponse');
// if they are in the dom...
if (sel && resp) {
// ... then attach event listener.
sel.addEvent('change', function(event) {
// this == sel.
var value = this.get("value"); // cache getter.
if (value === '') {
return false; // do nothing if not selected/
}
// otherwise, it will run the request
new Request.HTML({
method: "get", // or post.
data: {
extension: value // etc etc, can add more object properties and values
},
url: 'http://domain.co.nz/index.php',
onComplete: function(r1, r2, html, js) {
resp.set('html', html);
}
}).send();
});
} // end if
})(); // end closure.
you should really look at some tutorials and examples and the documentation for Request and Request.HTML/JSON/JSONP
an example, similar to yours that works for jsfiddle through its echo testing service (slightly different data object that simulates the response)
http://www.jsfiddle.net/dimitar/TXHYg/3/
instead of document.id('ExtensionResponse') you can write $('ExtensionResponse')
an if you only update a content of a element you can use the update parameter from Request.HTML.
new Request.HTML({
url : 'http://domain.co.nz/index.php',
data: 'extension='+ sel.getSelected().get('value'),
update: $('ExtensionResponse')
}).send();
#medrod;
That's right about the $(), but using the latest version of mootools + making sure Jess stays library safe, document.id() is a much safer option for compatibility.
you need to build the rest of your form, and populate it, with in the result of the ajax request.
eg: http://domain.co.nz/index.php?extension=
start your first HTML form with only the drop down, then your ajax'd script will build and populate the rest of the form.
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.
I have a draggable div, that needs to be dropped on a droppable. If it is dropped correctly, the droppable calls an AJAX request. If the draggable does not have a valid id or the AJAX request fails, the draggable should be reverted to it's original position. Is that something that can be done with jQuery?!
Any help is greatly appreciated!!
$("div.draggable").livequery(function(){
$(this).draggable({
revert: 'invalid',
distance: 20
})
});
$("#trash").droppable({
tolerance: 'touch',
drop: function(event, ui)
{
var item = ui.draggable;
var id = item.attr('id');
if (id)
{
$.ajax(
{
type: "POST",
url: "delete.php",
data: "id=" + id,
success: function(html)
{
if (html)
{
item.remove();
}
else
{
// FAILED AFTER AJAX
// is it possible to revert the draggable from here??
}
}
});
}
else
{
// FAILED BEFORE AJAX
// is it possible to revert the draggable from here??
}
}
});
I had the same problem,
You can simply do:
item.css({"top":0, "left":0});
tip: draggable has relative position.
Im not too familiar with jquery - but id suggest using the prototype framework (along with scriptaculous) - within prototype you can definately achieve this effect.
If you can guess what it's original position was in the fail block, just use a selector to find it and the manipulation functions to remove it from its current position and move it to the old one.
If you need to, perhaps you can store the original position (parent and child-index) when it is dragged, then move it back there when it fails