Steps to run a function for updating a JSON data file

I currently have a Leaflet map displaying weather data retrieved from a Json source. There is already a function in place that updates the data every x minutes using setInterval.

    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)

}

Now, I want to be able to trigger this function manually by clicking a button. Something like

        L.easyButton( 'fas fa-cloud-sun-rain', function(){
            myfunction()
        }, 'Refresh', {
            position: 'topright'
        })

However, I'm unsure about what exactly needs to be called to achieve this. Any insights would be greatly appreciated.

Answer №1

To optimize your code, extract the fetching logic from within the setInterval function. Create a new function for fetching data and use it both in the setInterval and when defining your button.

You can implement something similar to this:

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);

                replaceMarkers(currentFactor);

            }
        },
        error: function (err) {
            console.error('There is no data available for today.', err)
        }
    });
}

// Set up the interval for fetching data
setInterval(fetchData, 300000);

// Set up the button functionality
L.easyButton( 'fas fa-cloud-sun-rain', fetchData, 'Conditions', {
    position: 'topright'
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for sending JSON parameter to asmx web service using $ajax

Below are my parameters: var pMaster = '{"tid" : "474", "fid":"2"}'; var pDetail = '[{"recid":5618,"tid":"474","itemid":"1435","nar1":""},{"recid":5619,"tid":"474","itemid":"1203","nar1":""},{"recid":5620,"tid":"474","itemid":"1205","nar1": ...

Swift Parsing JSON

How can I extract data from a JSON file that includes numerical elements? I need to retrieve specific information from a JSON object in Swift, but some of the keys are numbers and I'm unsure how to access those values. I've been able to successf ...

Ruby 1.9.3 causing issues with instant variables not displaying in AJAX response for Rails 3.2.1

Recently, I've encountered a perplexing issue. Every time I initiate an AJAX request, it returns an error indicating that the instance variables are "nil". It appears as though the controller isn't sending any data back. Oddly enough, this exact ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

Troubleshooting: Vue.js Component template not displaying items with v-for loop

I recently implemented a method that calls an AJAX request to my API and the response that it returns is being assigned to an array. In the template section, I am using the v-for directive to display the data. Surprisingly, it only renders once after I mak ...

Error: The variable "$this" has not been defined in the AJAX function

Recently, I've been delving into the world of javascript and ajax. I'm trying to create a dynamic select option list similar to this: https://i.sstatic.net/qELIf.png However, when attempting to compile using Google Chrome Developer tools (F12), ...

Sharing numerous pictures in a single line using comma-separated pathways

I am trying to enhance my code by allowing users to select multiple images simultaneously and on submit click, I want to store the file paths in MySQL database as comma-separated values in a single row. Below is the code snippet that I have implemented: C ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

Tips for dynamically updating the id value while iterating through a class

Here's the HTML snippet I am working with: <div class="info"> <div class="form-group"> <label class="control-label col-sm-2">Title</label> <div class="col-xs-10 col-sm-8"> <inpu ...

The process of updating the value of an element in local storage with JavaScript

Most of the time we have an object stored in our localStorage. let car = { brand: "Tesla", model: "Model S" }; localStorage.setItem("car", JSON.stringify(car)); https://i.sstatic.net/qWEkE.png I am now eager to update the value of "model". H ...

Strange alignment issues occurring solely on certain PCs

Currently, I am in the process of developing a website for a client who has requested that it be an exact replica of the mockup provided. However, I have encountered some issues with the headers and certain divs that contain background elements. Surprising ...

How come the date displays as 21/1/2015 instead of 21/1/2015 in Android after parsing the JSON data?

Currently, I am utilizing the DatePicker functionality in my code and transmitting the value via JSON. The desired format for the value is 21/1/2015 without the extra backslashes. How can I resolve this issue? DatePickerDialog.OnDateSetListener date = n ...

Error message displayed by console when attempting to parse JSON data that is in array

After receiving a simple array as my JSON response: [35,55] The Chrome network inspector confirms that it is valid JSON. However, when attempting to parse the xhr.responseText using JSON.parse, I am confronted with the error: Uncaught SyntaxError: Unexpe ...

Tips for staying safe from UNLINK security vulnerabilities in PHP

I am currently using UNLINK in conjunction with PHP and AJAX. I understand that this approach is risky as it allows anyone to delete files. However, I require the use of AJAX because I do not want the page to reload when deleting files. My main concern is ...

Using Jquery to Connect a Change Event to Child Elements

<form id="duration"> <label for="change-chart-type-24H" > ; <input style="display:none;" name="chart-type" id="change-chart-type-24H" type="radio" value="24H">24H ...

Adding a class to an element in AngularJS

I have a question about entering empty values in an input field and highlighting its boundary. I added a new class 'warning' for this purpose and created the following code. HTML: `<body ng-app="TestPage"> <form ng-controller="TestFor ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

Shade the entire td column in different colors depending on the characteristics of th

I am working with a table and here is the code for it: <table> <thead> <tr> <th style="width: 40%; text-align: center; vertical-align: center;">Nr.<br> crt.</th> <th style="font-weight: bold; wi ...

Is there a way to utilize a variable as a key within an object?

Can this be done? Take a look at a practical example from the real world: var userKey = "userIdKey"; chrome.storage.sync.set({ userKey: "Hello World" }, function () { chrome.storage.sync.get(userKey, function (data) { console.log("In sync:", ...

Using Highmaps with PHP and JQuery Ajax: Passing a parameter to the current page and retrieving it with PHP

I have successfully created a map using PHP and Highmaps (from Highcharts libraries) that retrieves data from a SQL Server database. Everything is working smoothly so far! However, I am now facing the challenge of sending a value from the map to another PH ...