Using Polymer to automatically update the DOM when a JSON file is modified

I am currently developing a modal window to add data to a JSON file and then display that data in the DOM. The issue I'm facing is that while the data gets saved to the file successfully, it doesn't reflect immediately on the DOM. The technology stack used includes iron-ajax for handling asynchronous requests.

     <div>
         <iron-ajax 
            auto
            url="areas.json"
            handle-as="json"
            last-response="{{response}}"
            on-response="responseHandler" 
          ></iron-ajax> 

          <div class="modal"></div>

        <div class="layout vertical">        
            <div class="layout horizontal">
                <template class="" id="esquema" is="dom-repeat" items="{{response}}" as="item">
                    <div class$="iron-flex {{item.type}}">{{item.name}}</div>
                </template>
            </div>
         </div>
    </div>

The snippet provided above shows how the data is fetched from the JSON file and rendered on the DOM. However, a specific function call is required to update the dom upon adding new data using the modal:

    addData: function(){
            var selectedItem = this.options[this.selectedIndex];            
            nuevo.push({"name": this.$.numberArea.value, 
                        "level": "1", 
                        "type": selectedItem.area});
            this.$.numberArea.value = null;
            this.$.areaSelect.selected = null;    
        },

In order to refresh the 'id="esquema"', I attempted calling this.$.esquema.render() within the function, but unfortunately, it didn't work as expected. Your guidance or suggestions on resolving this issue would be highly appreciated.

Thank you in advance for your support!

Answer №1

After taking the time to thoroughly review everything on my computer, I noticed a crucial mistake in your code. When attempting to use .render or .generateRequest, you were executing it within the dom-repeat template instead of the correct location, which is the iron-ajax element. The correction should look like this:

<iron-ajax 
    auto
    id="ajaxRequest"
    url="areas.json"
    handle-as="json"
    last-response="{{response}}"
    on-response="responseHandler"></iron-ajax> 

Following that, remember to include

this.$.ajaxRequest.generateRequest();
inside your function like so:

addData: function(){
    var selectedItem = this.options[this.selectedIndex];            
    nuevo.push({"name": this.$.numberArea.value, 
                "level": "1", 
                "type": selectedItem.area});
    this.$.numberArea.value = null;
    this.$.areaSelect.selected = null;
    this.$.ajaxRequest.generateRequest();
},

If we consider your current responseHandler function, it probably resembles something similar to this:

responseHandler: function(d){
    this.whereDataIsStored = d.detail.response;
}

To further enhance this functionality, you can add an asynchronous call to ensure that iron-ajax repeats periodically. This interval is specified in milliseconds, as demonstrated below:

responseHandler: function(d){
    this.whereDataIsStored = d.detail.response;
    this.async(function(){
        this.$.ajaxRequest.generateRequest();}, 5000);
},

This modification enables data storage in a property before triggering an automatic request every 5000 seconds for updated data retrieval. Ultimately, this should reflect in your dom-repeat component.

For additional information on async, refer to the provided link.

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

Delay the execution of the function in AngularJS until the browser has finished rendering completely and the view-model synchronization cycle has ended

I'm uncertain about the appropriate title for this inquiry, so please correct me if I am mistaken. Suppose that upon page refresh (load), I require an animated scroll to an anchor based on the current location's hash (I am aware of ngAnchorScrol ...

Transmit information to a webpage using jQuery AJAX and the .data() function as you navigate to the page

<script> function sendUserData(username){ $.post("userprofile.php", { username:username } ); document.location.href="userprofile.php"; } $(document).on('click','#userprofile',function(){ var username=$(this).data('id4&apo ...

Modifying the autocomplete feature to showcase options in a dropdown menu

I have a form that requires country states to be displayed in a dropdown menu. Despite having autocomplete functionality, I am only able to see the response as an array in the console.log when searching for a specific state. I have tried to switch from aut ...

How can I reset the DefaultValue of my Autocomplete input field after submitting?

Is there a way to reset the default value of my <TextField> inside Autocomplete after form submission? Even after submitting the form, the state of formValues remains as the default value. What can I do to fix this issue? I've attempted to mod ...

Use ajax to add rows to the second-to-last table

I am facing a situation where I have a table with 25 default rows. When scrolling to the bottom of the table, I want to dynamically insert another set of 25 rows. Everything is functioning correctly, but in a specific scenario, I need to preserve the last ...

Is it possible to incorporate jQuery into an AngularJS project?

When it comes to testing, AngularJS is a framework that supports test-driven development. However, jQuery does not follow this approach. Is it acceptable to use jQuery within Angular directives or anywhere in AngularJS for manipulating the DOM? This dilemm ...

How to extract cookie value in a node.js application using socket.io

How can I retrieve cookie values in a node server using socket.io? Whenever a socket sends a message to the server, I need to check the value of the cookie. However, I only want to obtain the cookie value and not the session cookie as done in Express. r ...

Whenever I attempt to incorporate the 'var' keyword within a for loop alongside setTimeOut, I encounter unusual output

Here's the code snippet I'm working with: for (var i = 1; i <= 5; i++) { setTimeout(function () { console.log(i); }, 1000); } I'm confused about the output of this code. When I run it, I see the number 6 printed in the c ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

Send only specific attributes from a class using Struts' JSON capabilities

Apologies, I am struggling to come up with a concise title for this question. Therefore, the title may not be very clear. I have created an action class that carries out certain business logic. Within the Action Class: class ActionClass extends ActionSu ...

Understanding the Class Syntax in Node.js

I'm having trouble understanding how to retrieve the value from a Node JS Class [Trying to use [Symbol.iterator '']]alert(Hello, ${this.name}!); Is there another way to approach this? class User { name = "Anonymous"; sayHi() { ...

Error encountered with the OpenAI API: "The module 'openai' does not have a defined export for 'Configuration'"

I'm encountering an issue while attempting to make an API call to the GPT-3.5 API from OpenAI; all imports from OpenAI are resulting in a 'has no exported member' error. import { Configuration, OpenAIApi } from "openai"; import { a ...

Unable to update JSON response in Firefox browser

Within my MVC view, I have an HTML SPAN with the class "displayText" that contains attributes for "typeId" and "idValue". The goal is to retrieve the DisplayText property from a database table based on the provided "typeId" and "idValue". Since there are ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...

Identical Identifiers in jQuery Tab Elements

Currently, I am utilizing the jQuery Tabs library within a small application. Within this page, there are 5 tabs that load content using Ajax. However, an issue arises when a tab is loaded and remains in the browser's memory along with its HTML elemen ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

When new AJAX content is loaded, Isotope container fails to properly target the new objects and instead overlaps the existing ones

My webpage loads all content through an AJAX call. Initially, I tried placing my isotope initialization code inside a document ready function, but it didn't work as expected: $(function(){ container = $('#content'); contain ...

Encountering a TypeError indicating that the asterisk is not functioning as a proper function

Whenever I run my server.js file, an error keeps popping up: TypeError: routing is not a function This occurs in the following line of code: routing(app); In my routing.js file, the content looks like this: // JavaScript source code var friends = requ ...