How to use date range picker along with ajax

徘徊边缘 提交于 2019-12-24 03:39:28

问题


I am using date range picker javascript library To select range of date from user

                  $('#date_range').daterangepicker({
                    arrows:true,
                    dateFormat: 'd-M-yy',
                    rangeSplitter: 'to',
                    datepickerOptions: {
                         changeMonth: true,
                         changeYear: true,
                         minDate: new Date("01/01/2011") //Account created date
                    },
                    closeOnSelect: true,
                    onChange: function(){
                                    //ajax call goes here

                                    }
                  });

In my ajax call i am updating the screen with date range. but this on change function runs two times and ajax returns old date value. If need to use ajax functionality with on change function of date range picker.

If any one find solution for using onchange function at once with correct from and to date, intimate me please. Thanks in Advance


回答1:


Reading the documentation you find

onChange: function, callback that executes whenever the date input changes (can happen twice on range selections).

I have setup a little demo http://jsfiddle.net/ByzYX/16/

So onChange seems to be the wrong callback for your solution. I am not really sure what you want to update on screen and why you do ajax requests but you could try a if condition to execute you ajax call only once.

So onOpen set a flag to true and after performing ajax call set it to false. In onChange check this flag.




回答2:


I did it this way:

$('#date_range').daterangepicker({
    "startDate": "01/01/2016",
    "endDate": "07/27/2016"
    }, function(start, end, label) {
        $.ajax({
            url:"/your_url",
            method: "GET", // or POST
            dataType: "json",
            data: {from: start.format('YYYY-MM-DD'), to: end.format('YYYY-MM-DD')},
            success:function(result) {
                console.log("sent back -> do whatever you want now");
            }
        });
    });

This function works like $("#date_range").change(function(){});, but it has some parameters too.

You might want to change the date string to a valid date where you receive it, in case you want to do some filtering.

I found about this function on http://www.daterangepicker.com/, look there for more examples! :)



来源:https://stackoverflow.com/questions/5308092/how-to-use-date-range-picker-along-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!