I get an array with the geolocation JavaScript, then I want to pass this array to a php script via ajax to process it and get an processed array back. Unfortunately it seems that the passed array to php is always NULL, I have no idea why.
My JavaScript/jQuery:
dataArray = [];
var lat = pos.coords.latitude;
dataArray.push({'lat':lat});
var lon = pos.coords.longitude;
dataArray.push({'lon':lon});
var identifier = 'ajax';
dataArray.push({'identifier':identifier});
console.debug(dataArray);
$.ajax({
async: true,
type: 'post',
cache: false,
url: 'custom.php',
data: {myJson: dataArray},
dataType : 'json',
success: function(data){
console.debug(data);
var json = $.parseJSON(data);
console.debug(json);
alert(json);
}
});
My php:
$JSArray['array'] = json_decode($_POST['myJson'], true);
$_SESSION['jsonArray'] = $JSArray['array'];
var_dump($_SESSION);
The result is always ["jsonArray"]=> NULL.
try this one. it works for me
(function($){
if(navigator.geolocation){return;}
var domWrite = function(){
setTimeout(function(){
throw('document.write is overwritten by geolocation shim. This method is incompatible with this plugin');
}, 1);
},
id = 0
;
var geoOpts = $.webshims.cfg.geolocation.options || {};
navigator.geolocation = (function(){
var pos;
var api = {
getCurrentPosition: function(success, error, opts){
var locationAPIs = 2,
errorTimer,
googleTimer,
calledEnd,
endCallback = function(){
if(calledEnd){return;}
if(pos){
calledEnd = true;
success($.extend({timestamp: new Date().getTime()}, pos));
resetCallback();
if(window.JSON && window.sessionStorage){
try{
sessionStorage.setItem('storedGeolocationData654321', JSON.stringify(pos));
} catch(e){}
}
} else if(error && !locationAPIs) {
calledEnd = true;
resetCallback();
error({ code: 2, message: "POSITION_UNAVAILABLE"});
}
},
googleCallback = function(){
locationAPIs--;
getGoogleCoords();
endCallback();
},
resetCallback = function(){
$(document).unbind('google-loader', resetCallback);
clearTimeout(googleTimer);
clearTimeout(errorTimer);
},
getGoogleCoords = function(){
if(pos || !window.google || !google.loader || !google.loader.ClientLocation){return false;}
var cl = google.loader.ClientLocation;
pos = {
coords: {
latitude: cl.latitude,
longitude: cl.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: $.extend({streetNumber: '', street: '', premises: '', county: '', postalCode: ''}, cl.address)
};
return true;
},
getInitCoords = function(){
if(pos){return;}
getGoogleCoords();
if(pos || !window.JSON || !window.sessionStorage){return;}
try{
pos = sessionStorage.getItem('storedGeolocationData654321');
pos = (pos) ? JSON.parse(pos) : false;
if(!pos.coords){pos = false;}
} catch(e){
pos = false;
}
}
;
getInitCoords();
if(!pos){
if(geoOpts.confirmText && !confirm(geoOpts.confirmText.replace('{location}', location.hostname))){
if(error){
error({ code: 1, message: "PERMISSION_DENIED"});
}
return;
}
$.ajax({
url: 'http://freegeoip.net/json/',
dataType: 'jsonp',
cache: true,
jsonp: 'callback',
success: function(data){
locationAPIs--;
if(!data){return;}
pos = pos || {
coords: {
latitude: data.latitude,
longitude: data.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: {
city: data.city,
country: data.country_name,
countryCode: data.country_code,
county: "",
postalCode: data.zipcode,
premises: "",
region: data.region_name,
street: "",
streetNumber: ""
}
};
endCallback();
},
error: function(){
locationAPIs--;
endCallback();
}
});
clearTimeout(googleTimer);
if (!window.google || !window.google.loader) {
googleTimer = setTimeout(function(){
//destroys document.write!!!
if (geoOpts.destroyWrite) {
document.write = domWrite;
document.writeln = domWrite;
}
$(document).one('google-loader', googleCallback);
$.webshims.loader.loadScript('http://www.google.com/jsapi', false, 'google-loader');
}, 800);
} else {
locationAPIs--;
}
} else {
setTimeout(endCallback, 1);
return;
}
if(opts && opts.timeout){
errorTimer = setTimeout(function(){
resetCallback();
if(error) {
error({ code: 3, message: "TIMEOUT"});
}
}, opts.timeout);
} else {
errorTimer = setTimeout(function(){
locationAPIs = 0;
endCallback();
}, 10000);
}
},
clearWatch: $.noop
};
api.watchPosition = function(a, b, c){
api.getCurrentPosition(a, b, c);
id++;
return id;
};
return api;
})();
$.webshims.isReady('geolocation', true);
})(jQuery);
jQuery(window).ready(function(){
navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000});
function successCallback(pos) {
$('#localstore').
load("geo?latitude="+ pos.coords.latitude +"&longitude=" + pos.coords.longitude, function()
{
$('#storefinder').hide();
$('#localstore').show();
});
}
function errorCallback(pos) {
/*
$('#storefinder').show();
$('#localstore').hide();
*/
}
});
There are multiple points are which your script can be failing.
I would test each step and see where it fails (by commenting out the echo statments one at a time):
echo $_POST['myJson'];
$JSArray['array'] = json_decode($_POST['myJson'], true);
//echo $JSArray['array'];
$_SESSION['jsonArray'] = $JSArray['array'];
//var_dump($_SESSION);
Also you ajax call should contain alert(data) without parseJSON, since the server is not sending JSON back, it is just echoing out a var_dump:
$.ajax({
async: true,
type: 'post',
cache: false,
url: 'custom.php',
data: {myJson: dataArray},
dataType : 'html', // change back to json when you send json from server
success: function(data){
console.debug(data);
//var json = $.parseJSON(data);
//console.debug(json);
//alert(json);
alert(data);
}
});
Related
Say I have a function as following. alert_danger returns the error message in red box. check_empty checks if a value posted from form is empty or not.
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
Now when I want to return the function value using jSON it's not returning the same. The following error is occuring:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
What seems to be the problem here?
Here is my jQuery if needed!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
Consider the following.
PHP
<?php
function checkEmpty($postValue, $msg){
return $postValue == null ? array("status" => "error", "message" => "Empty Value") : array("status" => $postValue, "message" => $message);
}
header('Content-Type: application/json');
echo json_encode(checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!"););
?>
JavaScript
function redirectTo(url, time) {
if (!url) {
return false;
}
time = time != undefined ? time : 0;
setTimeout(function() {
window.location.href = url;
}, time);
}
$(".action").click(function() {
$(this).closest("form").submit();
});
$("form").submit(function(event) {
event.preventDefault();
var type = $(this).find(".type").val();
var dataString = $(this).serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = $(this).attr("action");
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: dataString,
cache: true,
beforeSend: function() {
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json) {
if (json.status == "error") {
$(".message").html("<div class='alert alert-danger error'>" + json.message + "</div>").fadeIn();
} else {
$('.message').html("<div class='alert alert-danger'>" + json.message + "</div>").fadeIn();
$("html, body").animate({
scrollTop: $(".message").offset().top
}, "slow");
btnElement.html(btnValue);
if (type == 'admin') {
if ($('.message').find('#responseBox').hasClass('alert-success')) {
redirectTo("dashboard.php", 1000);
}
}
}
}
});
return false;
});
Typically, it is bad practice to use language X to generate code in language Y. Try decoupling the two languages by making data their only interface -- don't mingle the code.
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
You have to be careful to not confuse echo and return, they do very different things.
https://www.php.net/manual/en/function.echo.php
https://www.php.net/manual/en/function.return.php
Since you're passing back JSON data to the AJAX Call, I would advise wrapping your HTML inside the callback versus sending it back inside the JSON.
I think you should take a look at your success function. I think it normally runs before the page loads. So, its possible none of the html your referencing in there exists yet. So move it out to a function like this:
success: function(json) {
doSomething();
}
function doSomething(json){
$( document ).ready(function() {
console.log('page has loaded now modify your html with jquery'+json);
}
}
Im trying to display an error message to saying that , When result is 0 from database (mysql)
that will be an error message.
The code below im trying to use ajax to get SQL result and when it return 0 error will be display.
$.ajax({
type: "POST",
url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
dataType: "json", // serializes the form's elements.
success: function (result) {
var chart = c3.generate({
bindto: '#piepie',
data: result.value,
color: {
pattern: ['#f35213', '#f1af4c'] },
pie: { title: "Productivity", }
});
},
error: function() {
if (result.percentage==undefined){
alert ('Data are not ready yet!!');
} else {
alert(result.percentage);
}
}
});
$.ajax({
type: "POST",
url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
dataType: "json", // serializes the form's elements.
success: function (result) {
if (result.value == "0"){
alert ('ERROR!!');
} else {
var chart = c3.generate({
bindto: '#piepie',
data: result.value,
color: {
pattern: ['#f35213', '#f1af4c'] },
pie: { title: "Productivity", }
});
}
},
error: function() {
alert ('Error');
}
});
Try this
if (result.percentage.length==0){ // THIS IS WHAT YOU NEED.
alert ('ERROR!!');
} else {
// YOUR CODE GOES HERE.
}
As you have commented you are getting result as '{"percentage":[]}'. So you have percentage property as an array with length 0. So, you need to test that only.
Try this!
if ((typeof result !== " undefined") && (result !== null) && (result == 0)){
alert("YourErrorMessageHere");
}
If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.
Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});
I have index.php and getting problem with to decode the json array.. please help i am new to this..
<script>
$(document).ready(function () {
$("#slider_price").slider({
range: true,
min: 0,
max: 100,
step: 1,
values: [0, 100],
slide: function (event, ui) {
$("#app_min_price").text(ui.values[0] + "$");
$("#app_max_price").text(ui.values[1] + "$");
},
stop: function (event, ui) {
var nr_total = getresults(ui.values[0], ui.values[1]);
$("#results").text(nr_total);
},
});
$("#app_min_price").text($("#slider_price").slider("values", 0) + "$");
$("#app_max_price").text($("#slider_price").slider("values", 1) + "$");
});
function getresults(min_price, max_price) {
var number_of_estates = 0;
$.ajax({
type: "POST",
url: 'search_ajax.php',
dataType: 'json',
data: {
'minprice': min_price,
'maxprice': max_price
},
async: false,
success: function (data) {
number_of_estates = data;
}
});
return number_of_estates;
}
And search_ajax.php
<?php
require_once('includes/commonFunctions.php');
// take the estates from the table named "Estates"
if(isset($_POST['minprice']) && isset($_POST['maxprice']))
{
$minprice = filter_var($_POST['minprice'] , FILTER_VALIDATE_INT);
$maxprice = filter_var($_POST['maxprice'] , FILTER_VALIDATE_INT);
$query = mysql_query("SELECT * FROM cars WHERE min_range >= $minprice AND max_range <= $maxprice");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows);
}
?>
and the problem is i just want to print $rows in specific div "number_results".. how to decode that json array?
are you sure about the data you are passing is in json format
i think it should be
'{"minprice": "min_price", "maxprice":"max_price"}'
you cannot just return ajax returned value from a function since ajax is async...the function will already return number_of_estates , by the time ajax call completes.
use callback or just call a function and append your returned text there
..
stop: function( event, ui ) {
getresults(ui.values[0], ui.values[1]);
},
...
function getresults(min_price, max_price)
{
var number_of_estates = 0;
$.ajax({
type: "POST",
url: 'search_ajax.php',
dataType: 'json',
data: {'minprice': min_price, 'maxprice':max_price},
async: false,
success: function(data)
{
number_of_estates = data;
$("#results").text(number_of_estates);
}
});
}
however ajax is called each time the stop funnction occurs so be careful.
I am currently working away with FullCalendar, which is pretty cool and has done a lot of neat stuff for me. The only problem I'm having is that if I edit an event, and then try and create another event the javascript seems to hold onto the initial events data.
I am using calendar.fullCalendar('unselect') when I need the link to end, but it doesn't seem to make a difference no matter what I do. I'm hoping you guys might be able to see something I'm overlooking.
<script type='text/javascript'>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
selectable: true,
unselectAuto: true,
selectHelper: true,
editable: true,
select: function(start, end, allDay) {
//var title = prompt('Event Title:');
//var desc = prompt('Event Description:');
//calendar.fullCalendar('unselect');
$('#eventStart').val(start);
$('#eventEnd').val(end);
$('#eventAllDay').val(allDay);
$('#formName').fadeIn();
$('.closeSchedule a').click(function(){
$('#formName').fadeOut('slow');
$('#calendar').fullCalendar('unselect');
//alert(jsEvent);
});
},
events: [
<?php
$first = true;
foreach ($events as $event)
{
if ($first == true)
{
$comma = '';
$first = false;
}
else
{
$comma = ',';
}
echo $comma."
{
id: '".$event->id."',
title: '".addSlashes($event->title)."',
start: '".$event->start."',
end: '".$event->end."',
allDay: ".$event->allDay."
}";
$first = false;
}
?>
],
eventClick: function(event) {
//alert(event.id);
$.ajax({
url: './schedule/getEdit/'+event.id,
success: function(data) {
var formEmpty = $('formName').html();
$('#formName').html(data);
$('#formName').fadeIn('fast');
$('.closeSchedule a').click(function(){
$('#formName').fadeOut('slow');
$('#calendar').fullCalendar('unselect');
});
$('#deleteEvent').live('click', function(){
var answer = confirm("Are you sure you wish to delete this event?")
if (answer){
$.ajax({
type: "POST",
url: "./schedule/deleteEvent/"+event.id,
success: function(msg){
$('#formName').fadeOut('fast');
calendar.fullCalendar( 'removeEvents', [event.id ] )
$('#calendar').fullCalendar('unselect');
}
});
}
});
$('#updateEvent').live('click', function(){
var title = $('#eventName').val();
var trainerID = $('#eventTrainer').val();
var trainer = $('#eventTrainer option:selected').text();
var classID = $('#eventType').val();
var eventType = $('#eventType option:selected').text();
var eventStart = $('#eventStart').val();
var eventEnd = $('#eventEnd').val();
var eventAllDay = $('#eventAllDay').val();
if (eventAllDay == 'false')
{
allDay = false;
}
else
{
allDay = true;
}
// This runs the ajax to add the event to the database.
newData = 'title='+title+'&trainerID='+trainerID+'&classID='+classID+'&start='+eventStart+'&end='+eventEnd+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/updateEvent/"+event.id,
data: newData,
success: function(msg){
event.title = title;
calendar.fullCalendar('rerenderEvents');
//calendar.fullCalendar('unselect');
$('#calendar').fullCalendar('unselect');
}
});
$('#formName').fadeOut('fast');
$('#eventName').val('');
$('#eventTrainer').val();
$('#eventType').val();
});
}
});
},
eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
newData = 'start='+event.start+'&end='+event.end+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/updateEventTime/"+event.id,
data: newData,
success: function(msg){
}
});
},
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
newData = 'start='+event.start+'&end='+event.end+'&allDay='+event.allDay
$.ajax({
type: "POST",
url: "./schedule/updateEventTime/"+event.id,
data: newData,
success: function(msg){
}
});
}
});
$('#submitEvent').click(function(){
$('#calendar').fullCalendar('unselect');
var title = $('#eventName').val();
var trainerID = $('#eventTrainer').val();
var trainer = $('#eventTrainer option:selected').text();
var classID = $('#eventType').val();
var eventType = $('#eventType option:selected').text();
var eventStart = $('#eventStart').val();
var eventEnd = $('#eventEnd').val();
var eventAllDay = $('#eventAllDay').val();
if (eventAllDay == 'false')
{
allDay = false;
}
else
{
allDay = true;
}
// This runs the ajax to add the event to the database.
newData = 'title='+title+'&trainerID='+trainerID+'&classID='+classID+'&start='+eventStart+'&end='+eventEnd+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/addEvent",
data: newData,
success: function(msg){
var description = '<ol><li>'+title+'</li><li>'+trainer+'</li><li>'+eventType+'</li><li class="eventID hide">'+msg+'</li>';
calendar.fullCalendar('renderEvent',
{
id: msg,
title: title,
description: description,
start: eventStart,
end: eventEnd,
allDay: allDay
},
true // make the event "stick"
);
calendar.fullCalendar('unselect');
//calendar.fullCalendar( 'rerenderEvents' )
}
});
$('#formName').fadeOut('fast');
$('#eventName').val('');
$('#eventTrainer option:selected').removeAttr('selected');
$('#eventType option:selected').removeAttr('selected');
});
});
</script>
At this point, I feel like I've tried it all, and I'm just hoping a fresh set of eyes will see what I missed.
Ok took a quick look it looks like you aren't initializing the form with a blank form for the add action in the "select:" function of your full calendar:
In your event click you are doing this:
$('#formName').html(data);
I don't see where you are clearing that with a blank form for a new event. (might have just missed it there is a lot of code there)
Let me know.