muther muther - 1 year ago 97
Ajax Question

jquery change function with AJAX

I m using API to show the prayer timings according to months and i want to display the current month prayer timings when I load the page and my code is given below.how can i display the current month prayer timing when page loads.



$(document).ready(function() {
$('.months').change(function() {
var $month = $('.months').val();
var d = new Date();
var curr_year = d.getFullYear();
var $monthText = $(".months option:selected").text();
$('#selected-month').html('Prayer Timings For '+ $monthText);
function splitTime(time) {
return time.split(" ", 1);
}
$.ajax({
method: 'GET',
url: 'https://api.aladhan.com/calendarByCity?city=Hyderabad\
&country=IN&month=' + $month + '&year=' + curr_year + '&method=2&school=1',
success: function(data) {
var rowCount = $('#myTable >tbody >tr').length;
if (rowCount > 0) {
$("#myTable > tbody > tr").remove();
}
$.each(data.data, function(i, v) {
var timing = v.timings;
$('#myTable > tbody:last-child').append('<tr>\
<th>' + v.date.readable + '</th>\
<th>' + splitTime(timing.Fajr) + '</th>\
<th>' + splitTime(timing.Sunrise) + '</th>\
<th>' + splitTime(timing.Dhuhr) + '</th>\
<th>' + splitTime(timing.Asr) + '</th>\
<th>' + splitTime(timing.Maghrib) + '</th>\
<th>' + splitTime(timing.Isha) + '</th>\
</tr>');

})
},
error: function(data) {
alert('There is no response from server side');
}
});
})

<form>
<select class="form-control months">
<option>Select Month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</form>




Answer Source

When the page loads you can set the dropdown to the current month, and then trigger the change event.

JSFiddle : https://jsfiddle.net/421o6x9L/

//Date.getMonth returns 0-11

var month = new Date().getMonth() + 1;
if (month < 10) {
    month = "0" + month;
}
$('.months').val(month).trigger("change");

Put that in the end of your $(document).Ready();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download