Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way, the JavaScript file responsible for handling AJAX requests can parse the data and display markers and infowindows on the map.

  1. In the JavaScript file, there are two functions - searchAddress and removeAddress, triggered by user clicks on "cerca" or "cancella" buttons respectively. The purpose of these functions is to manipulate the JSON array to show or hide markers and infowindows on the map. After editing the code, I encountered new errors related to undefined variables and missing function definitions when interacting with the buttons.

Here's an update to the JS file:

// Updated JavaScript code will go here 

  1. This first JSON array contains information like latitudes, longitudes, titles, and content needed for the map visualization based on the parsed data from the JavaScript file.

[
{
"title": "Paolo", 
"latitude": 41.897115,
"longitude": 12.513300,
"content": "Cooperativa fornitrice di servizi sociali,<br/> Viale Eleonora D'Arborea 12<br/> 00162 Roma<br/> <a href='http://www.prassiericerca.com' target='_blank'>Prassi e Ricerca</a>",
"icon": "img/orange-dot.png",
"coords": "1, 1, 1, 20, 18, 20, 18 , 1",
"type": "poly"
},
// Additional entries...
]
      

  1. This second JSON array contains updated information meant to replace the previous data once the file names are switched between .json and .json0. The loading of JSON files and mapping of new data are handled within the JS file.

[
{
"title": "Bar dei Pini", 
"latitude": 41.897115,
"longitude": 12.513300,
"content": "Specialita Gelato Artigianale<br/> Viale Eleonora D'Arborea 12<br/> 00162 Roma<br/> <a href='http://www.prassiericerca.com' target='_blank'>Prassi e Ricerca</a>",
"icon": "img/pink-dot.png",
"coords": "1, 1, 1, 20, 18, 20, 18 , 1",
"type": "poly"
},
// Additional entries...
]

The page does not require reloads as long as one of the JSON files maintains the .json extension after renaming.

Answer №1

If you want to simplify things, consider keeping the file names as is instead of renaming them. The XMLHttpRequest operation, being client-side, cannot change file names on the server like "json1.json". What's holding you back from restructuring your code so that the part fetching JSON data is turned into a function with the URL passed as an argument?

function Get(url){
  var xmlhttp = new XMLHttpRequest();
  console.log(url);
  var arr; 

  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      arr = JSON.parse(xmlhttp.responseText);
    }
  }
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
  return arr;
}

This approach allows you to fetch any needed files easily. For example:

markers = Get("http://www.example.com/json1.json");
markers.concat(Get("http://www.example.com/json2.json"));

You can also apply a similar method to handle your marker code. By putting it in a function, pass the "markers" variable as an argument to display them on the map.

In essence, dividing your code into functions helps optimize flow and promotes code reuse.

Answer №2

If I have understood your query correctly, here is a workaround that may solve your problem. It appears that the JSON attributes like title, latitude, longitude, content, icon, coords, and type in both files are similar, with only the latitude and longitude values varying. In this scenario, why not create a Plain Old Java Object (POJO) with these properties and use the Gson API to marshal the JSON data into these POJOs? This way, json1 will be represented by pojo object1 and json2 by pojo object2. Then, you can add these objects to a list and pass the list to a JsonParser to generate a combined JSON data from both files. Finally, this JsonParser-generated data can be sent to a JavaScript file. I hope this explanation clears up any confusion.

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

Tips for updating one-time binding data in AngularJS

I am currently facing an issue with a div that displays details such as mobile number, name etc. in the format: {{::mobilenumber}}, {{::name}} Within this div, there is a button that when clicked should populate the same values in a new form However, des ...

Maintaining the active style of Asp.NET 4.0 Menu control even after the mouse is released

Utilizing a standard asp.net menu in an asp.net 4.0 web application, this setup is for a standard web application and not any version of MVC applications currently available. The issue at hand is relatively straightforward. CSS styles are applied to the d ...

Guide to setting a dynamic print style without affecting the screen media

In my report, there is a details section below. The screen provides instructions to view the details with a button that toggles the list's visibility. When printing the report, I only want the instructions to show if the list is visible. If the list ...

PHP fails to retrieve posted data from AJAX when using serializeArray()

I have been struggling with a form that is utilizing jQuery validation and AJAX to submit data to a PHP script for backend processing. The AJAX function uses serializeArray() to collect the form values, but despite my best efforts, I cannot seem to success ...

What is the best way to evaluate user input against a string retrieved from process.stdin.on()?

I'm having trouble comparing a string with user input from process.stdin.on as it always returns false. //Let's say the user inputs 'hello' every time. process.stdin.on('data', userInput => { let text = userInput.toStrin ...

Tips for maintaining JSON data in CK Editor

I'm having an issue where my JSON data is not being displayed in CKEditor when using this code function retrieveRules(){ $.ajax({ url: "api", type: "POST", data: { version:'0.1' }, ...

The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes: <div ng-controller="MyCtrl"> <div ng-view>Some content</div> myVar: {{myVar}} </div> Along with an Angular controller: myModule.controller('MyCtrl', function($s ...

What steps can be taken to stop clients from sending an OPTION request prior to each GET?

Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...

"An issue arises where the bokeh plot fails to render when generating a

I have been working on embedding a bokeh plot within a webpage served by a simple Flask app. I am using the embed.autoload_server function that I found in the bokeh embed examples on github. While everything seems to be functioning correctly on the Python ...

tips for exporting database information to an excel file with the help of ajax request and javascript

Recently, I built an application using NDWS with sapui5 _javascript. Within the application, there is a table that contains data synced with the server's database. My goal is to retrieve this data from the table and export it to an Excel document. Her ...

Error encountered during AJAX POST request: NETWORK_ERR code XMLHttpRequest Exception 101 was raised while using an Android device

Here is the ajax post code that I am using: $.ajax({ type: "POST", url: "http://sampleurl", data: { 'email':$('#email').val(), 'password':$('#password').val(), }, cache: false, ...

Creating a bottom bar using React and Material UI

I'm currently working on implementing a footer that will be displayed on every page of my Next.js application. To style this, I am utilizing Material UI. The following component is responsible for defining the layout across all pages of the app: impo ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

What is the right height and width to use in CSS?

I find it challenging to decide when to use rem, em, px, or % in web design. Although I know the definitions of each unit, I struggle with knowing the appropriate situations to utilize them. What guidelines should I follow to determine which one to use? ...

The Infinite scroll feature in Fuel UX is ineffective when a specific height is not defined for the

In my current project, I am utilizing Bootstrap and Fuel UX v3.4.0 with the goal of implementing Infinite scroll throughout my entire page. Unfortunately, I have encountered difficulties in achieving this implementation. By replicating the infinite scroll ...

When a radiobutton is clicked, a jQuery call to a PHP function triggers an AJAX request which results in a JavaScript function becoming unrefer

Currently, I have a situation where two radio buttons are representing different products. When one of them is clicked, the goal is to update the price displayed on the website based on the selected product. Everything seems to be working fine when using t ...

Can you explain the meaning of 1__qem?

While looking at the default styles applied to HTML elements for Google Chrome, I came across this information on this page: p { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1__qem; -webkit-margin-start: 0; -web ...

Converting a timestamp to a date format within AngularJS interpolation

Is there a way to send a timestamp, such as 1519357500, to HTML and then convert it into a date format while using interpolation? I attempted the following approach but unfortunately it did not work: {{moment($ctrl.myTimestamp).format('MMMM Do YYYY, ...

Move the text above within the footer using materialize framework

I'm facing an issue with my materialize footer's text disappearing when I set the height to 35px. Whenever I decrease the size of the footer, the text goes off the screen. How can I adjust it so that it stays visible? <footer style="positio ...

Unable to locate "Gruntfile.js" Node module for task execution

I am currently in the process of developing a module that enables node to execute Grunt tasks via the command line. This Node module is globally installed at : C:\Users\pcharpin\AppData\Roaming\npm\node_modules\task-app ...