How to execute a function to update a json source - javascript

I have a Leaflet map that show some weather data from a Json source. I have already a function that update the data every x minutes by a setInterval function.
setTimeout(function () {
refreshId = setInterval(function () {
$.ajax({
method: 'get',
dataType: 'text',
url: 'myURLfile.json',
success: function (data) {
if (data) {
markers = [];
var withoutMarkers = data.slice(10);
markers = JSON.parse(withoutMarkers);
//console.log(markers);
replaceMarkers(currentFactor);
}
},
error: function (err) {
console.error('there is not date for today.', err)
}
})
}, 300000);
},10000)
}
What I would to do now is assign this funtion to a button to execute the refresh fuction manually.
Something like
L.easyButton( 'fas fa-cloud-sun-rain', function(){
myfunction()
}, 'Refresh', {
position: 'topright'
})
But I don't understand what I have to call exactely to do it.

Factor your fetch code out of setInterval and use your newly made function both in setInterval and your button definition.
Something like
function fetchData() {
$.ajax({
method: 'get',
dataType: 'text',
url: 'myURLfile.json',
success: function (data) {
if (data) {
markers = [];
var withoutMarkers = data.slice(10);
markers = JSON.parse(withoutMarkers);
//console.log(markers);
replaceMarkers(currentFactor);
}
},
error: function (err) {
console.error('there is not date for today.', err)
}
});
}
// setup your interval
setInterval(fetchData, 300000);
// setup your button
L.easyButton( 'fas fa-cloud-sun-rain', fetchData, 'Condizioni', {
position: 'topright'
})

Related

ajax loading before document despite using when().then() function with leaflet JS

Here is what the console reads:
Uncaught TypeError: Cannot read property 'addTo' of undefined
I am currently working with leaflet JS and before the page loads, there is quite a number of Ajax calls going on so that the website can render the acquired data for the user.
I have used two particular methods to synchronize certain ajax calls which rely on the previous. One method is passing the next ajax call into the complete function, whilst another is the when().then() function
The objective with the function below, which is called with the window.onload method, is to determine the users location using the javascript navigator, set the map, and proceed with the ajax calls as mentioned above.
$(window).on('load', function() {
//Pre-loader Jquery
if ($('#preloader').length) {
$('#preloader').delay(200).fadeOut('slow', function() {
$(this).remove();
});
}
//Determine users location, initiate leaflet map, synchornised ajax calls to retreive country core information
navigator.geolocation.getCurrentPosition((success) => {
const crd = success.coords;
onLoadLat = crd.latitude;
onLoadLng = crd.longitude;
currentMap = L.map('map').setView([onLoadLat, onLoadLng], 5);
mapTileLayer.addTo(currentMap);
$.ajax({
url: "libs/php/openCage.php",
type: "POST",
dataType: "JSON",
data: {
latLng: onLoadLat + "+" + onLoadLng
},
success: function(data, textStatus, jqXHRs) {
iso_a2 = data["results"][0]["components"]["ISO_3166-1_alpha-2"];
},
complete: function() {
//Retreive GeoJson file, mark polygon and set initial map for to reflect user location
$.ajax({
url: "libs/php/getCountryBorder.php",
type: "POST",
dataType: "JSON",
data: {
countryCode: iso_a2
},
success: function(geoData, txtSt, jq) {
//Reference details of existing country for further API's and functionality
nameOfCountry = geoData["properties"]["name"];
//Use the index to target the array and create polygon border on map
targetMapData = L.geoJSON(geoData, {
style: borderStyle
});
targetMapData.addTo(currentMap);
currentMap.fitBounds(targetMapData.getBounds(), {
padding: [50, 50],
});
},
complete: function() {
$.ajax({
url: "libs/php/keyCountryInfo.php",
type: "POST",
dataType: "JSON",
data: {
country_code: iso_a2
},
success: function(data, textStatus, jqXHR) {
capitalCity = data["capital"];
currencyCode = data.currencies[0].code;
coordinates = [...data.latlng];
$("#timezoneList").empty();
$("#countryName").text(data["name"]);
$("#region").text(data["region"]);
$("#sub-region").text(data["subregion"]);
$("#countryFlag").attr("src", data["flag"]);
$("#population").text(numeral(data["population"]).format(0, 0));
$("#capital").text(data["capital"]);
$("#timezoneList").text(data["timezones"][0]);
},
complete: function() {
$.when(**getPopularCities()**, getCityWeatherList(), getWikiEntries(onLoadLat, onLoadLng), getGeoNameId(), getCountryImages(), getPublicHolidays(), getLatestExchange(), populateSelect()).
then(function(data, textStatus, jqXHR) {
infoEasyBtn.addTo(currentMap);
wikiEasyBtn.addTo(currentMap);
currencyEasyBtn.addTo(currentMap);
covidEasyBtn.addTo(currentMap);
newsEasyBtn.addTo(currentMap);
weatherEasyBtn.addTo(currentMap);
airportMarkers.addTo(currentMap);
cityMarkers.addTo(currentMap);
siblingMarkers.addTo(currentMap);
});
}
})
}
})
}
})
})
});
within the onload function above, is the getPopularCities() method, which is where the issue is. I have set markers to be shown on the map, but there is one group of markers which do not load, from within that function
Get Popular Cities Method
function getPopularCities() {
let cityPopulation = [];
cityMarkers = new L.MarkerClusterGroup();
if (mainLayer) {
currentMap.removeControl(mainLayer);
}
$.ajax({
url: "libs/php/getCountryCities.php",
type: "POST",
dataType: "JSON",
data: {
getCountryIso: iso_a2
},
success: function(success, textStatus, jqXHRs) {
$("#top10CityTable").empty();
let cityList = success["cities"]; //grab all the cities from the response
//create an array in global variable named cityPopulation, to contain all the markers
cityList.sort((a, b) => {
if (a["population"] > b["population"]) {
return -1
} else {
return 1
}
})
cityList.forEach((element, index) => {
let formatedPop = numeral(element["population"]).format(0, 0);
//depending on how many citys have returned, title the heading accordingly
if (cityList.length < 10) {
$("#top10CityHeading").text("Major Cities")
}
if (cityList.length >= 10) {
$("#top10CityHeading").text("Top 10 Most Populated Cities");
}
//stop index at 9 to get data of top 10 most populated cities for modal section
if (index <= 9) {
$("#top10CityTable").append(`<tr><td>${element["name"]}</td><td>${formatedPop}</td></tr>`)
}
cityMarkers.addLayer(L.marker([element["latitude"], element["longitude"]], {
icon: populatedCities
}).bindPopup(`<h3>${element["name"]}</h3></br>Population: ${formatedPop}`));
})
//create a new overlay prop/value pairing in the global overlays variable
overlays["Major Cities"] = cityMarkers;
},
error: function(text, xh, errorThrown) {
console.log(errorThrown);
},
complete: function() {
let siblingsMapArr = [];
siblingMarkers = new L.MarkerClusterGroup();
$.ajax({
url: "libs/php/getCountrySiblings.php",
type: "POST",
dataType: "JSON",
data: {
countryGeoId: geoNameId
},
success: function(success, textStatus, jqXHRs) {
$("#countrySiblings").empty();
let siblingsArr = success["geonames"];
siblingsArr.sort((a, b) => {
if (a["population"] > b["population"]) {
return -1
} else {
return 1
}
})
let top10Sib = siblingsArr.slice(0, 10);
top10Sib.forEach((element, index) => {
let formatedPop = numeral(element["population"]).format(0, 0);
let rank = index + 1;
siblingMarkers.addLayer(L.marker([element["lat"], element["lng"]], {
icon: citySiblings
}).bindPopup(`<h3>${rank}. ${element["countryName"]}</h3><br/>Population: ${formatedPop}`));
$("#countrySiblings").append(`
<tr>
<td>${element["countryName"]}</td>
<td>${formatedPop}</td>
<td>${element["lat"]} / ${element["lng"]}</td>
</tr>`)
})
overlays["Top 10 Siblings (By Population)"] = siblingMarkers;
},
complete: function(success, data, jq) {
$.ajax({
url: "libs/php/getAirports.php",
type: "POST",
dataType: "JSON",
data: {
countryCode: iso_a2
},
success: function(success, txtStatus, jqXHR) {
let airportsArr = [];
airportMarkers = new L.MarkerClusterGroup();
const airportsList = success["data"];
airportsList.forEach((element) => {
airportMarkers.addLayer(L.marker([element["location"]["latitude"], element["location"]["longitude"]], {
icon: airportIcon
}).bindPopup(`<h3>${element["name"]["original"]}</h3></br>ICAO: ${element["icao"]}</br>Elevation: ${element["elevationFeet"]}<br/>Classification: ${element["classification"]}`));
})
overlays["Airports"] = airportMarkers;
mainLayer = L.control.layers(baseMaps, overlays);
mainLayer.addTo(currentMap);
airportMarkers.addTo(currentMap);
cityMarkers.addTo(currentMap);
siblingMarkers.addTo(currentMap);
}
})
}
})
}
})
}
The markers saved in the variable airportMarkers and cityMarkers appear on the map as well as the leaflet control panel, but the siblings markers do not.
So Im guessing the safe bet is that it is not bringing the data back in time before the page loads? Does anyone have a solution for this or perhaps I have done something wrong in my code?

Why do the ajax requests fire multiple times

I have a form inside a modal that either saves a memo when one button is clicked or deletes it when another is clicked. The items get saved/deleted but the request count multiplies with each click. I'm getting 4 of the same request etc. How do i stop this. do i have to unbind something?
$('#modal').on('show.bs.modal', function (e) {
var origin = $(e.relatedTarget);
var memoId = origin.attr('data-id');
$('#modal').click(function(event){
if($(event.target).hasClass('memo-save')) {
event.preventDefault();
var memoText = $(event.target).parent().parent().find('textarea').val();
var memo = {
memo: memoText,
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/add-memo?memo=' +memo+'&id=' + memoId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Saved');
}
});
} else if($(event.target).hasClass('memo-delete')) {
event.preventDefault();
var memoText = "";
var memo = {
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/remove-memo?id=' + itemId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Deleted');
}
});
}
});
});
you can move the $('#modal').click outside the $('#modal').on('show.bs.modal' that way it will not re-add the listener each time the modal is shown

Problem: pass some parameters in ajax call (post)

I have 2 functions: one to add and another to delete. I would like to reuse the same ajax call to send the parameters that are added or deleted. How can I optimize my function?
Here is my code at the moment
jQuery(document).ready(function () {
function ajaxCall(action, callback) {
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
},
success: function (response) {
if (response.error == true) {
alert(response.errors.join('\n'));
}
else if (response.status == "DONE") {
callback(false);
}
},
error: function (xhr) {
console.log("Error: ", JSON.stringify(xhr));
callback(true);
}
});
}
jQuery('#ajax_add').click(function (event) {
event.stopPropagation();
var id = jQuery('#id').val();
var price = jQuery('#price').val();
//I want to send two variables: id, price
ajaxCall("addData", function (error) {
if (error) {
alert("Error!.");
}
else {
alert("It's OK!");
}
});
});
});
The function to delete is similar to "addData" function, it also calls "ajaxCall" and will send parameters to remove.
I'm blocked and I do not know how to solve it, I hope you can give me some help, thanks
You could add a new argument to the ajaxCall function and send the parameters as an object them merge them with the data you've in the function like :
function ajaxCall(action, params, callback) {
Then in the ajax call :
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: $.extend(params, {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
}),
...
The call inside the event will be like :
ajaxCall("addData", {id: id, price: price}, function (error) {

jQuery wait for .each to finish and run ajax call

I have the following code:
var allChecks = [];
$('input[type=text]').each(function () {
var key = $(this).attr("id");
allChecks[key] = [];
}).promise()
.done(function () {
$('input[type=checkbox]').each(function () {
if (this.checked) {
var ref = $(this).attr('id');
$('.' + ref).each(function () {
allChecks[ref].push({
amount: $("#" + ref).text()
});
});
} else {
allChecks[ref].push({
amount: 0.00
});
}
}).promise()
.done(function () {
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: allChecks
},
url: '/process',
beforeSend: function () {
console.log("Processing your checks please wait...");
},
success: function (response) {
console.log(response);
},
error: function () {
console.log("Error");
}
});
});
});
My Ajax call runs but I see no data passed as parameters, like if the array allChecks is empty. As JavaScript runs synchronously, I'm expecting that whatever I place after each() will not run until each() is complete, so the Ajax call should run fine and nor give me no data passed as if the array allChecks is empty. Any help or solution on this would be appreciated. Thanks.

Vue.js 2: Get data from AJAX method

I'm new to Vue, and I'm attempting to grab the data via AJAX in a method.
I know the method is working.
Here's the Vue code:
Vue.component('sub-folder', {
props: ['folder'],
template: '{{folder.title}}'
});
var buildFoldersList = new Vue({
el: '#sub-folders',
data: {
foldersList: this.foldersList
},
methods: {
buildFolders: function () {
$.ajax({
url: base_url + 'api/folder/get_subfolders/' + browser_folder_id,
method: 'POST',
data: {
"folder_id": browser_folder_id
},
success: function (data) {
console.log("Data");
console.log(data);
this.foldersList = data;
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
}
});
Here's the HTML:
<div class="list-group" id="sub-folders">
<sub-folder v-for="folder in foldersList" :key="folder.folder_id" v-bind:folder="folder"></sub-folder>
</div>
At the moment, the containing template is running, but since the method isn't getting executed, there's no data.
I've tried everything I know to trigger the method, but I've run out of ideas.
It seems you are not calling the buildFolders method at all, you can call it from the created hook of vue.js like following:
var buildFoldersList = new Vue({
el: '#sub-folders',
data: {
foldersList: []
},
created () {
this.buildFolders()
},
methods: {
buildFolders: function () {
var self = this
$.ajax({
url: base_url + 'api/folder/get_subfolders/' + browser_folder_id,
method: 'POST',
data: {
"folder_id": browser_folder_id
},
success: function (data) {
console.log("Data");
console.log(data);
self.foldersList = data;
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
}
});
Also you can relook at how you are using this, as scope of this will change in $.ajax method as happened here, see the explanation here.

Categories

Resources