Ajax call with setInterval does not fetch new data from database - javascript

I am working on a project where i need to display users details depending on date and time after given interval.I am using below code but it does not work as per my requirement.
$(document).ready(function () {
$.ajax({
type: "Post",
url: "<?php echo site_url('registrationc/map')?>",
// data: "unit_id="+unitid,
data: { startDate: startdate, endDate: enddate, status: status },
success: function (data) {
marker(data);
},
});
refresh();
});
function refresh() {
setInterval(function () {
$.ajax({
type: "Post",
url: "<?php echo site_url('registrationc/map')?>",
// data: "unit_id="+unitid,
data: { startDate: startdate, endDate: enddate, status: status },
success: function (data) {
alert("success 2");
alert(data);
marker(data);
},
});
}, 30000);
}
function marker_map(data){
var locations=JSON.parse(data);
alert(data);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(20.5937,78.9629),//{ lat: 20.5937, lng: 78.9629 }
mapTypeId: google.maps.MapTypeId.ROADMAP//HYBRID //SATELLITE//TERRAIN
});
var marker, i;
//var contentString ='<div id="iw-container"><div class="iw-title" align="center"></div>';
for (i = 0; i < locations.length; i++)
{
var url="http://maps.google.com/mapfiles/ms/icons/";
if(locations[i]['status']=="green")
{
url+="green"+"-dot.png";
}
else if(locations[i]['status']=="yellow")
{
url+="yellow"+"-dot.png";
}
else if(locations[i]['status']=="orange")
{
url+="orange"+"-dot.png";
}
else
{
url+="red"+"-dot.png";
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['longi']),
icon:{url:url},
map: map});
var land=locations[i][1];
var contentString = '<div id="content">'+
'<div class="iw-title">Patients Details</div>'+
'<h5 id="firstHeading" class="firstHeading">Patients Details</h5>'+
'<div id="bodyContent">'+
'<p>'+
'<p>Attribution: Uluru'+
'</p>'+
'</div>'+
'</div>';
google.maps.event.addListener(marker, 'click', (function(marker, i) {
var content = '<div id="iw-container">' +
'<div class="iw-title">'+locations[i]['firstname']+'</div>' +
'<div class="iw-content">' +
'<div class="iw-subTitle">STATUS:'+locations[i]['status']+'</div>' +
'<div class="iw-subTitle">PERSONAL DETAILS</div>'+
'<h6>Age:'+locations[i]['age']+'</h6>'+
'<h6>Gender:'+locations[i]['gender']+'</h6>'+
'</div>' +
'<div class="iw-bottom-gradient"></div>' +
'</div>';
var infowindow = new google.maps.InfoWindow({content:content});
return function() {
//infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
//marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
}
})(marker, i));
}
}
ajax function is called after given time interval but it does not fetch new data from database.for example if there are three entries in database during 1st call and than after given interval 2nd call also fetch only three entries even if there are five entries.how do i change the code to get expected result.

Issue seems with data that you pass to ajax call. Like start date and end date.
Please try below sample:
function getStats() {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes();
var time1 = " 00:00";
var status = "all";
var today = new Date();
var dd = String(today.getDate()).padStart(2, "0");
var mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
var yyyy = today.getFullYear();
var startdate = yyyy + "-" + mm + "-" + dd + "" + time1;
var enddate = yyyy + "-" + mm + "-" + dd + " " + time;
return { startdate, enddate, status };
}
$(document).ready(function () {
let { startdate, enddate, status } = getStats();
$.ajax({
type: "Post",
url: "<?php echo site_url('registrationc/map')?>",
data: { startDate: startdate, endDate: enddate, status: status },
success: function (data) {
marker(data);
},
});
refresh();
function refresh() {
setInterval(function () {
let { enddate } = getStats();
$.ajax({
type: "Post",
url: "<?php echo site_url('registrationc/map')?>",
data: { startDate: startdate, endDate: enddate, status: status },
success: function (data) {
marker(data);
},
});
}, 30000);
}
});

Related

Return value from Webmethod and Alert at javascript ajax

I tried to alert numberOfHours in javascript ajax which is from WebMethod.
I am not so sure how to retrieve value from WebMethod and parse it to ajax for alert message.
Below here is webmethod and ajax that I am working on :
//WebMethod aspx.cs
[System.Web.Services.WebMethod]
public static string GetFirstDateAndLastDate(DateTime firstDayDate, DateTime lastDayDate,string ddlName)
{
//String daresult = null;
string firstDay = firstDayDate.ToString("yyyy/MM/dd");
string lastDay = lastDayDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
//testing purpose only
SqlCommand com = new SqlCommand("SELECT sum([NumberOfHours]) FROM [LoginDB1].[dbo].[tbOT] where [Date] between '" + firstDay + "' And '" + lastDay + "' AND name = + '" + ddlName + "'", conn);
//say for example numberOfhours get "9.0" hours from sql
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
//trying with arraylist but not able to return
// ArrayList rows = new ArrayList();
//foreach (DataRow dataRow in dt.Rows)
// rows.Add(string.Join(";", dataRow.ItemArray.Select(item =>
item.ToString())));
return "OK";
}
//Script aspx
var selectedDate = $("[id$=datepicker]").datepicker('getDate');
var firstDay = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1);
var lastDay = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0);
var data = {};
data.firstDayDate =firstDay.getFullYear() + "-" + (firstDay.getMonth() + 1) + "-" + firstDay.getDate();
data.lastDayDate = lastDay.getFullYear() + "-" + (lastDay.getMonth() + 1) + "-" + lastDay.getDate();
data.ddlName = $("[id$=ddlName] option:selected").text();
console.log("Log Data", data)
$.ajax({
type: "POST",
url: "SupervisorOTRequest.aspx/GetFirstDateAndLastDate",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == "OK") {
//alert return value
}
});
Kindly Advise and Thanks in Advance.

Google timeline chart should be blank

I'm creating a Google TimeLine chart, which works well except for the fact that when there's no data to return a broken text is shown inside the chart area, which should just remain blank.
I already checked if it was some wrong return from my DB (I commented all the DB access code to ensure the list that fills the chart would return empty) and the error persist.
So my best shot is that the error is with some misconfiguration of the Google timeline chart area itself.
This is the code that works perfectly when there is data return:
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChartTimeLine);
function reloadChartTimeLine(){
var inidate=document.getElementById("inidate").value;
var enddate=document.getElementById("enddate").value;
var idRack=document.getElementById("idRack").value;
jQuery.ajax({
type: "POST",
url: '<c:url value="/tracking/searchRackTimeLineByDate" />',
data: { idRack: idRack, inidate: inidate, enddate:enddate },
success: function(data) { drawChartTimeLine(data);}
});
}
function drawChartTimeLine(response) {
var data = new google.visualization.DataTable();
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
data.addColumn( 'string','Local' );
data.addColumn( 'string','Situação' );
data.addColumn( 'date', 'Início' );
data.addColumn( 'date', 'Fim' );
if(response!=undefined){
response.forEach(function (row) {
data.addRow([
row.local,
row.movementStatus,
new Date(row.startDate),
new Date(row.endDate)
]);
});
}
data.insertColumn(2, {type: 'string', role: 'tooltip', p: {html: true}});
var dateFormat = new google.visualization.DateFormat({
pattern: 'd/M/yy HH:mm:ss'
});
var options = {
tooltip: {isHtml: true},
hAxis:{format:"dd/M" },
timeline: { showBarLabels: false},
colors: ['#0f434c','#a30404'],
};
var ticks = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticks.push(data.getValue(i, 0));
var duration = (data.getValue(i, 4).getTime() - data.getValue(i, 3).getTime()) / 1000;
var days = parseInt( duration / 86400 )
var hours = parseInt( duration / 3600 ) % 24;
var minutes = parseInt( duration / 60 ) % 60;
var seconds = duration % 60;
var tooltip = '<div class="ggl-tooltip"><span>' +
data.getValue(i, 1) + '</span></div><div class="ggl-tooltip"><span>' +
data.getValue(i, 0) + '</span>: ' +
dateFormat.formatValue(data.getValue(i, 3)) + ' - ' +
dateFormat.formatValue(data.getValue(i, 4)) + '</div>' +
'<div class="ggl-tooltip"><span>Duração : </span>' +
days + 'd '+hours + 'h ' + minutes + 'm ' + seconds + 's ';
data.setValue(i, 2, tooltip);
}
options["hAxis"]["ticks"] = [0]
chart.draw(data, options);
}
Here's a screenshot to the issue (there's no data to be returned in the selected period);
https://imgur.com/yKN9j9j
I selected and pasted the broken text and it goes "31/12" although in the chart canvas only a broken "/12" is visible. This same text occurs for every empty period.
A little late but I managed to show the chart without the canvas area when there's nothing to return just adding a lenght condition to use the response from ajax and putting all the code inside this condition as shown below; thanks for all the tips:
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChartTimeLine);
function reloadChartTimeLine(){
var inidate=document.getElementById("inidate").value;
var enddate=document.getElementById("enddate").value;
var idRack=document.getElementById("idRack").value;
jQuery.ajax({
type: "POST",
url: '<c:url value="/tracking/searchRackTimeLineByDate" />',
data: { idRack: idRack, inidate: inidate, enddate:enddate },
success: function(data) { drawChartTimeLine(data);}
});
}
function drawChartTimeLine(response) {
var data = new google.visualization.DataTable();
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
data.addColumn( 'string','Local' );
data.addColumn( 'string','Situação' );
data.addColumn( 'date', 'Início' );
data.addColumn( 'date', 'Fim' );
if(response!=undefined && response.length>0){
response.forEach(function (row) {
data.addRow([
row.local,
row.movementStatus,
new Date(row.startDate),
new Date(row.endDate)
]);
});
data.insertColumn(2, {type: 'string', role: 'tooltip', p: {html: true}});
var dateFormat = new google.visualization.DateFormat({
pattern: 'd/M/yy HH:mm:ss'
});
var options = {
tooltip: {isHtml: true},
hAxis:{format:"dd/M" },
timeline: { showBarLabels: false},
colors: ['#0f434c','#a30404'],
};
var ticks = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticks.push(data.getValue(i, 0));
var duration = (data.getValue(i, 4).getTime() - data.getValue(i, 3).getTime()) / 1000;
var days = parseInt( duration / 86400 )
var hours = parseInt( duration / 3600 ) % 24;
var minutes = parseInt( duration / 60 ) % 60;
var seconds = duration % 60;
var tooltip = '<div class="ggl-tooltip"><span>' +
data.getValue(i, 1) + '</span></div><div class="ggl-tooltip"><span>' +
data.getValue(i, 0) + '</span>: ' +
dateFormat.formatValue(data.getValue(i, 3)) + ' - ' +
dateFormat.formatValue(data.getValue(i, 4)) + '</div>' +
'<div class="ggl-tooltip"><span>Duração : </span>' +
days + 'd '+hours + 'h ' + minutes + 'm ' + seconds + 's ';
data.setValue(i, 2, tooltip);
}
options["hAxis"]["ticks"] = [0]
chart.draw(data, options);
}
}

Working with Dates in Sapui5

How can I get the current date, current year, current month, and current week in sapui5? This is the code I started with:
var oType = new sap.ui.model.type.Date();
oType = new sap.ui.model.type.Date({ source: {}, pattern: "MM/dd/yyyy" });
I have no idea where to go from here. Any help would be greatly appreciated.
EDIT: How do I get the following javascript function into a sapui5 table?
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function dateFunction() {
var today = new Date();
var dd = addZero(today.getDate());
var MM = addZero(today.getMonth() + 1);
var yyyy = today.getFullYear();
var hours = addZero(today.getHours());
var min = addZero(today.getMinutes());
var sec = addZero(today.getSeconds());
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
today = MM + '/' + dd + '/' + yyyy + " " + hours + ":" + min + ":" + sec + " " + ampm;
}
To get Current Date:
there is NO predefined function in SAPUI5, hence use native JavaScript Method:
var oDate = new Date();
How to put date in a table?
JS Fiddle
var oData = {
results: [{
name: "Today",
date: new Date()
}, {
name: "Someday",
date: new Date("2015/01/01")
}, {
name: "New Year",
date: new Date("2016/01/01")
}]
}
var oModel = new sap.ui.model.json.JSONModel(oData);
// create table:
var oTable = new sap.m.Table({
columns: [
new sap.m.Column({
header: new sap.m.Label({
text: "When"
})
}),
new sap.m.Column({
header: new sap.m.Label({
text: "Date"
})
})]
});
var oType = new sap.ui.model.type.Date({
pattern: "MM/dd/yyyy"
});
var oTemplate = new sap.m.ColumnListItem({
cells: [
new sap.m.Text({
text: "{name}"
}),
new sap.m.Text({
text: {
path: 'date',
type: oType
}
})]
});
oTable.setModel(oModel);
oTable.bindItems("/results", oTemplate);
oTable.placeAt("content");
Update: Based on comment request
All you need is this:
var oType = new sap.ui.model.type.Date({
pattern: "MM/dd/yyyy"
});
oTable.addColumn(new sap.ui.table.Column("today", {
label: new sap.m.Label({
text: {
path: 'today',
type: oType
}
})
sortProperty: 'today',
filterProperty: 'today'
}));

json response date format to user defined date format

Following code is returning $("#dob") and $("#anniversery") date as 2014-04-01T00:00:00
My code
<script>
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#customerName").autocomplete({
source: function(request, response) {
$.ajax({
url: "ajaxCustomer",
dataType: "json",
data: {
str: $("#customerName").val(),
maxRows: 12
},
success: function(data) {
response($.map(data.customerList, function(item) {
console.log(item);
return {
label: item.customerName,
value: item.customerName,
id: item.customerId,
address: item.address,
dob: item.dob,
mobno: item.mobno,
annversery: item.anniversery
}
}));
},
error: function(data) {
alert(data.supplierList);
console.log(typeof data);
console.log(data);
alert('error');
}
});
},
minLength: 1,
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#mobNo").val(ui.item.mobno);
$("#address").val(ui.item.address);
$("#dob").val(ui.item.dob);
$("#anniversery").val(ui.item.annversery);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
</script>
I want $("#dob") and $("#anniversery") its value in yyyy/mm/dd format
How to do this
I tried $("#dob").val(format_date(ui.item.dob));
function format_date(dt) {
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
document.write(dt);
document.write(year + '/' + month + '/' + day);
}
This is not working.
You have to cast the value you get from ui.item.dob to a Date.
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
Then in your format_date function, remove the extra line at the bottom and put a return statement instead:
function format_date(dt) {
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
return dt;
}
You could use MomentJS
Apply format :
$("#anniversery").text(moment(ui.item.annversery).format('YYYY/MM/DD'));
var date = "2014-04-01T00:00:00";
var newDate = date.split("T")[0].replace(/-/g, "/");
console.log(newDate);
=> 2014/04/01
As already #display_name pointed you missed to parse the Date. Here a more simplified version of your code:
function format_date(dt) {
var dateString = new Date(dt); //parse the date
var formatedDate = dateString.getFullYear() + "/" +
('0'+ (dateString.getMonth() +1)).slice(-2) + "/" +
('0'+ dateString.getDate()).slice(-2);
return formatedDate; //return the formatted date to the input field
}
Now you can
$("#dob").val(format_date(ui.item.dob)); // incase if it is a textbox
try this..
var thisDate = "2013-01-01 00:00:00";
var thisDateT = thisDate.substr(0, 10);
You should create new Date object before using get functions:
var date = new Date(dt);
And then you can get the proper values:
var dd = date.getDate();
and so on.

Jquery Calendar disable dates using beforeShow and beforeShowDay

i have implemented code to disable dates using beforeShow and beforeShowDay callbacks
below code is for binding calendar to input
$("#start_on").datepicker({
onSelect: function(date) {
date_check(date);
}, minDate: 0, dateFormat: "yy-mm-dd",
beforeShow: get_booked,
beforeShowDay: disable_if_not_available
});
yes this is binding calendar to element
callback for beforeShow
function get_booked(inpput, inst) {
var D = new Date();
var month = (inst.selectedMonth == 0 ? D.getMonth() : inst.selectedMonth) + 1;
var year = (inst.selectedYear == 0 ? D.getYear() : inst.selectedYear);
dis_date = new Array();
$.ajax({
url: BASE_URL + "contest/get_booked",
data: {year: year, month: month, id:<?php echo (isset($contest_data->id)) ? $contest_data->id : 0; ?>},
dataType: "json", type: "POST",
success: function(data) {
for (var d in data) {
var D = data[d];
var start = D.start_on;
var d = start.split("-");
var sD = new Date(d[0], d[1] - 1, d[2]);
var end = D.end_on;
var d = end.split("-");
var eD = new Date(d[0], d[1] - 1, d[2]);
while (sD <= eD) {
dis_date.push(sD.getFullYear() + "-" + (sD.getMonth() + 1) + "-" + sD.getDate());
sD.setDate(sD.getDate() + 1);
}
}
}
});
}
callback for beforeShowDay
function disable_if_not_available(date) {
var y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate();
return [dis_date.indexOf(y + "-" + m + "-" + d) == -1];
}
problem with this is that disable_if_not_available is getting called before dis_date get filled from get_booked. currently disable_if_not_available return always true because dis_date is empty so what i want to do is to call/return disable_if_not_available only after i get response from get_booked
please ask if any doubt
This happens because the entire initialization of the datepicker ends before the ajax call returns any value.
what you could do is start the ajax call and when the call ends, call the initialization of the datepicker.
example:
...
...
$.ajax({
url: BASE_URL + "contest/get_booked",
data: {year: year, month: month, id:<?php echo (isset($contest_data->id)) ? $contest_data->id : 0; ?>},
dataType: "json",
type: "POST",
success: function(data) {
for (var d in data) {
var D = data[d];
var start = D.start_on;
var d = start.split("-");
var sD = new Date(d[0], d[1] - 1, d[2]);
var end = D.end_on;
var d = end.split("-");
var eD = new Date(d[0], d[1] - 1, d[2]);
while (sD <= eD) {
dis_date.push(sD.getFullYear() + "-" + (sD.getMonth() + 1) + "-" + sD.getDate());
sD.setDate(sD.getDate() + 1);
}
}
//CALL YOUR DatePicker Initialization
initDatePicker();
}
});
...
...
function initDatePicker(){
$("#start_on").datepicker({/*Initialization values*/});
}
Simple Solution for this.just use 'async:false' in your ajax call.
Example:
...
...
$.ajax({
url: BASE_URL + "contest/get_booked",
data: {year: year, month: month, id:id)) ? $contest_data->id : 0; ?>},
dataType: "json",
type: "POST",
async:false,
success: function(data) {
...
...

Categories