Jquery: Unable to add Json object to Ajax request - javascript

Overview: I am making a web tool that displays the total number of movies sold by different studios on digital platform using charts(Highcharts). These charts are dynamic so the user has a list of filters he can use to change the result.
Filter 1 - Studios:
Using this filter the user can select different studios whose sales he would wish to see.
Filter 2 - Period:
This is the duration during of time for which he would want to see the sales.
It is this filter that is giveing me the problem.
Basically the selection of the period doesnot get sent with the AJAX request and hence has no effect on the chart. The default value for the period (Set using the momentjs library) also goes with the AJAX request. It is the change in the period that doesnt get added to the request.
There is no error message as such.
The Code:
$(document).ready(function(){
var btnStudiosDiv = $('#btnStudios');
var getStudios = function ()
// Get all studio's from buttons with .active class
var studios = $('button.active', btnStudiosDiv).map(function () {
return $(this).val();
}).get();
// If no studio's found, get studio's from any button.
if (!studios || studios.length <= 0) {
studios = $('button', btnStudiosDiv).map(function () {
return $(this).val();
}).get();
}
return studios;
};
var periodFrom = (moment().format('WW')-11)
var periodTo = moment().format('WW')
var output = {};
var show = function (studios) {
output['Studios'] = studios,
var per = {Period: {"From":["W" + periodFrom],"To":["W" + periodTo]}};
$.extend(output, per);
$('.list').html(JSON.stringify(output)); //Display Json Object on the Webpage
$.ajax({ //Ajax call to send the Json string to the server
type: "POST",
data: {"jsontring": JSON.stringify(output)},
url: "http://localhost:8080/salesvolume" ,
contentType: "application/json",
dataType: "json",
cache: false,
beforeSend: function() {
$('#container').html("<img class = 'ajload' src='loading.gif' />");
},
success: function(data){
alert( ) ;
$('#container').highcharts(data);
},
error: function() {
alert("Something is not OK :(")
},
});
};
var timer; //To create a time delay of 2 Secs for every selection
$(".btn").click(function () {
$(this).toggleClass('active');
// Fetch studios
var studios = getStudios();
// Remove previous timeOut if it hasn't executed yet.
if(timer)
clearTimeout(timer);
// Wait 2 sec
timer = setTimeout(function () {
// Fill list with the studios
show(studios);
},2000);
});
// Show the json on page load
show(getStudios());
//Period Selector (Template used from http://jqueryui.com/datepicker/)
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('#weekpickerFrom').datepicker('widget').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('#weekpickerFrom').datepicker( {
showOn: "button",
buttonImage: "calendar2.gif",
buttonImageOnly: true,
buttonText: "Select date",
changeMonth: true,
changeYear: true,
showWeek: true,
showOtherMonths: false,
selectOtherMonths: false,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#weekpickerFrom').val(date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
output.Period.From = (date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
periodFrom = output.Period.From //Add Period from to the Json String
if(timer)
clearTimeout(timer);
timer = window.setTimeout(function() {$('.list').html(JSON.stringify(output))},2000); //Display Json Object on the Webpage
selectCurrentWeek();
},
beforeShow: function() {
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
}).datepicker('widget').addClass('ui-weekpickerFrom');
$('.ui-weekpickerFrom .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.ui-weekpickerFrom .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('#weekpickerTo').datepicker('widget').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('#weekpickerTo').datepicker( {
showOn: "button",
buttonImage: "calendar2.gif",
buttonImageOnly: true,
buttonText: "Select date",
changeMonth: true,
changeYear: true,
showWeek: true,
showOtherMonths: false,
selectOtherMonths: false,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#weekpickerTo').val(date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
output.Period.To = (date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
periodTo = output.Period.From //Add Period to to the Json String
if(timer)
clearTimeout(timer);
timer = window.setTimeout(function() {$('.list').html(JSON.stringify(output))},2000); //Display Json Object on the Webpage
selectCurrentWeek();
},
beforeShow: function() {
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
}).datepicker('widget').addClass('ui-weekpickerTo');
$('.ui-weekpickerTo .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.ui-weekpickerTo .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
});
It would be really helpful if someone could point out where I am going wrong.
Note: There are multiple other filter added on the tool, however for simplicity 1 have just mentioned the two important ones.

I think data should be like this
$.ajax({
type: "POST",
**data: "{\"jsontring\":" + JSON.stringify(output) + "}",**
url: "http://localhost:8080/salesvolume" ,
contentType: "application/json",
dataType: "json",
cache: false,
beforeSend: function() {
$('#container').html("<img class = 'ajload' src='loading.gif' />");
},
success: function(data){
alert( ) ;
$('#container').highcharts(data);
},
error: function() {
alert("Something is not OK :(")
},
});
In your Ajax request

Related

jquery UI datpicker highlight the week instead of day

I have this code for jquery UI datepicker modified to select a complete week, i want to highlight the current selected week, right now the activate date which is today is highlighted but i want it should the entire week starting from sunday
the code is already selecting the week when i clik on any row, but the only issue is on load it does not select the current week, it just select the todays date
Here is the code i am using
jQuery.browser = {};
(function () {
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
})();
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
changeMonth: true,
changeYear: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
any idea how can i do this
html is
<div class="week-picker"></div>
here is the fiddle
https://jsfiddle.net/6mbp3Lgn/
i want that today is 3rd nov, it should keep the first row selected because 3rd falls in first week and like that

How to highlight the date in calendar with different colors according to events?

This is my calendar java script code:
<script type="text/javascript">
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
</script>
This is my view page picture of calendar
From this calendar i have to highlight dates according to events that i have saved in the database(using colors).I don't have any idea about this.please help me to solve this problem.
You can reinitialize the date picker in Ajax success, like this
$.ajax({
type: "POST",
url: "ajax_url" ,
success: function(response) {
var highlight_dates = {};
highlight_dates[ new Date( '03/10/2020' )] = new Date( '03/10/2020' );
highlight_dates[ new Date( '02/21/2020' )] = new Date( '02/21/2020' );
$('#datepicker').datepicker({
beforeShowDay: function(date) {
var highlight = highlight_dates[date];
if( highlight ) {
return [true, "class-to-highlight", 'Special Event'];
} else {
return [true, '', ''];
}
}
});
} ,
});

Javascript/Jquery-UI make reusable function that checks if dateTo is after dateFrom

I have 2 datepickers. #datepicker0 and #datepicker1 and the following code to check if the date_from is after date_to:
$('#datepicker0').datepicker({
dateFormat: 'yy-mm-dd'
});
var valeDate = {
dateFormat: 'yy-mm-dd',
onSelect: function() {
if ($('#datepicker0').val() > $(this).val()) {
alert("Date problem");
$(this).val(null)
}
$(this).change();
}
}
$("#datepicker1").datepicker(valeDate).on("change", function() {
display("Change event");
I would like to remove the parameter #datepicker0 from the onSelect function in order to make the function reusable.
Could anyone show me how to make it?
function validateDate(datepicker, value) {
if (value > datepicker.val()) {
alert("Date problem")
datepicker.val(null)
}
datepicker.change()
}
var valeDate = {
dateFormat: 'yy-mm-dd',
onSelect: function() {
validateDate($(this), $('#datepicker0').val())
}
}
Next time, please address questions like this (everything works but code require modifications) to code review (https://codereview.stackexchange.com/)
finally i used this code:
function datepickerValidator(startDate,endDate) {
var datepickerFrom = startDate;
var datepickerTo = endDate;
// returns the millisecond obtained from the string 'dd-mm-yy'
function getTimeMillis(dateString) {
var splittedFrom = dateString.split("-");
var day = splittedFrom[0];
var month = splittedFrom[1];
var year = splittedFrom[2];
var dateTmp = new Date(year + "-" + month + "-" + day);
var timeMillis = dateTmp.getTime();
return timeMillis;
}
var validateDatePickerOption = {dateFormat: 'dd-mm-yy',
onSelect: function() {
from = getTimeMillis(datepickerFrom.val());
to = getTimeMillis($(datepickerTo).val());
if ( from > to ) {
alert("Date problem: value 'To' must be after 'From'");
$(this).val(null)
}
}
}
return validateDatePickerOption;
}
and for each datepicker:
var from = $("#From");
var to = $("#To");
var datepickerOption = datepickerValidator(from,to);
from.datepicker(datepickerOption);
to.datepicker(datepickerOption);

How to disable specific date materialize

Here is a javascript made by materialize, and I am trying to disable specific dates. But I tried a lot of code here but could not get any result from this.
<script>
var dateToday = new Date();
$('.datepicker').pickadate({
selectMonths: true,
selectYears: 40,
format: "yyyy-mm-dd",
min: dateToday,
max: new Date(2030, 11, 31),
closeOnSelect: true,
onOpen: function () {
this.clear();
},
onSet: function () {
var x,y,year,date,month;
x = $('.datepicker1').pickadate().val().toString();
y = x.split(/[ ,]+/);
date = y[0];
month = y[1];
year = y[2];
console.log(y[0]+" "+ y[1]+ " "+ y[2]);
if(date && month && year){
this.close();
}
}
});
$("#mcDateFrom").click(function(event) {
event.stopPropagation();
$("#mcDateFrom").first().pickadate("picker").open();
});
$("#mcDateTo").click(function(event) {
event.stopPropagation();
$("#mcDateTo").first().pickadate("picker").open();
});
</script>
I am also trying the below code also.
var array = ["2018-06-28","2013-03-15","2013-03-16"]
$('.datepicker').pickadate({
beforeShowDay: function(date){
var string = jQuery.pickadate.formatDate('yyyy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
But no result after trying a lot of things as well as this code. I need help. Thanks in advance.

Change range datepicker (jquery)

I have a question regarding jquery.ui datepicker.
I have a project where the week starts on Friday.
That I have no problem with that.
The thing is datepicker not find the way to make the select that I have for weeks, beginning with Friday and also select default Thursday click anywhere for that week.
In summary:
Week Starts Thursday.
The Selection of the week begins Thursday (range)
OnSelect Automatically switches to the selected week Thursday.
Can you help?
My code:
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
firstDay: 5,
dateFormat: "dd/mm/yy",
maxDate : "+0",
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
//window.location = '<?php echo HTTP_URI; ?>ranking/week?day=' + dateText + '';
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
Yeep! I find my own solution.
My code
$(function() {
var selectCurrentWeek = function(callback) {
window.setTimeout(function () {
$(".week-picker").find("a.ui-state-active").parents("tr").find("a.ui-state-default").each(function(key, node) {
$(this).addClass("ui-state-active");
});
callback();
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
firstDay: 5,
dateFormat: "dd/mm/yy",
maxDate : "+0",
onSelect: function(dateText, inst) {
selectCurrentWeek(function() {
var startDayy = $(".week-picker").find("a.ui-state-active").eq(0);
var EndDayy = $(".week-picker").find("a.ui-state-active").eq(6);
var startDay = startDayy.text();
var EndDay= EndDayy.text();
var monthStart = startDayy.parent().attr('data-month');
var monthEnd= EndDayy.parent().attr('data-month');
var yearStart = startDayy.parent().attr('data-year');
var yearEnd = EndDayy.parent().attr('data-year');
if(monthStart < 10){ monthStart = '0'+monthStart; }
if(monthEnd < 10){ monthEnd = '0'+monthEnd; }
var CompleteStartDay = startDay +'/'+ monthStart +'/'+yearStart;
var CompleteEndDay = EndDay +'/'+ monthEnd +'/'+yearEnd;
$('#startDate').text(CompleteStartDay);
$('#endDate').text(CompleteEndDay);
//window.location = '<?php echo HTTP_URI; ?>ranking/week?day=' + CompleteStartDay + '';
});
}
});
});

Categories