简体   繁体   中英

Jquery: Unable to add Json object to Ajax request

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM