通过Ajax传递日期值

I have two pass my calendar value through Ajax. The problem is, date value passing only after second try of selecting date and it is passing the first try value!!

The current result as an Example:

On first try I will select: 2017-03-01

selectvalueds = ‘ ‘

On second try I will select: 2015-05-30

Selectvalueds = ‘2017-03-01’

Important:! Due to some calculation i have to first copy the value of calendar to #start and then pass #start through Ajax to my php code. Javascript:

$('#calendar').change(function() {
    $('#start').val($(this).val());
});
    $('#calendar’).change(function(){
            var selectvalueds = $('#start').val();
            Unit_id.html('<option value="">Loading...</option>');
            if (selectvalueds == '') 
            {Unit_id.html(initial_Unit_html);} 
            else 
            {
                $.ajax({
                    url: 'index.php',
                    data:'option=com_myapp&task=getUnitsHTML&dsvalue='+selectvalueds,
                    success: function(output) {
                        Unit_id.html(output);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status + ' ' + thrownError);
                    }
                });
            }
         });

php:

 public function getUnitsHTML() {
         $jinput = JFactory::getApplication()->input;
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);           
         $sdate = date_create($jinput->get ('dsvalue'));   
         $mystartdate = date_format($sdate, "Y-m-d");         
         echo '<div>'.$mystartdate.'</div></br>';            
        }

You are binding 2 change events to the #calendar. Instead, try something like this:

function yourCalculation(start_val) {
    execute_whatever_you_want;
};
$('#calendar').change(function() {
    value = $(this).val()
    yourCalculation(value);

    var selectvalueds = value;
    Unit_id.html('<option value="">Loading...</option>');
    if (selectvalueds == '') {
       Unit_id.html(initial_Unit_html);
    } else {
       $.ajax({
              url: 'index.php',
              data:'option=com_myapp&task=getUnitsHTML&dsvalue='+selectvalueds,
              success: function(output) {
                   Unit_id.html(output);
              },
              error: function (xhr, ajaxOptions, thrownError) {
                   alert(xhr.status + ' ' + thrownError);
              }
       });
    }
 });

This will first get the value, execute your calculation function, then add the Loading option, check if the value is not empty and if it's not empty, start Ajax call.