Calls at intervals using polymer's iron-ajax

I have a basic Polymer frontend application. I am using ajax to retrieve data from the backend:

<iron-ajax id="getAjax"
  auto
  url="http://localhost:14039/InvoiceService/envelop/{{envelopId}}/invoices"
  handle-as="json"
  last-response="{{invoices}}">

The ajax call is successfully made at startup. When I use other iron-ajax components to make POST requests, I trigger

this.$.getAjax.generateRequest();
and it functions properly.

My question is, how can I set up a timer to automatically call this function? Essentially, I want to regularly "refresh" the page using iron-ajax. I came across some solutions on how to do it with JQuery, but I find myself getting confused with Polymer's properties, functions, internal functions, this.$, etc.

Answer №1

To implement delayed tasks in Polymer, you can utilize the async() method as outlined in the official documentation:

  • async(method, [wait]). This function calls the specified method asynchronously. If a wait time is provided, it executes tasks with microtask timing, occurring after the current method completes but before the next event from the event queue. The function returns a handle that allows for task cancellation.

  • cancelAsync(handle). Use this function to cancel a specific asynchronous task using its handle.

For example, the code snippet below defines _updateData(), which triggers an AJAX request after a 2-second delay. This can be utilized within an on-response handler of an <iron-ajax> element so that the request is automatically resent 2 seconds after each response:

Polymer({
  is: 'x-foo',
  _updateData: function() {
    this.async(function() {
      this.$.ajax.generateRequest();
    }, 2000);
  },
  _onResponse: function() {
    this._updateData();
  }
});

Check out the live demo below to see this functionality in action:

<head>
  <base href="https://polygit.org/polymer+1.11.1/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-ajax/iron-ajax.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <iron-ajax id="ajax"
                 auto
                 url="//jsonplaceholder.typicode.com/users/"
                 last-response="{{data}}"
                 on-response="_onResponse"
                 handleAs="json">
      </iron-ajax>
      <table>
        <template is="dom-repeat" items="[[data]]">
          <tr>
            <td>[[item.id]]</td>
            <td>[[item.name]]</td>
            <td>[[item.email]]</td>
          </tr>
        </template>
      </table>
      <div>
        <sup>See console log</sup>
      </div>
    </template>
    <script>
      HTMLImports.whenReady(function() {
        Polymer({
          is: 'x-foo',
          _updateData: function() {
            this.async(function() {
              this.$.ajax.generateRequest();
            }, 2000);
          },
          _onResponse: function() {
            console.log('received response');
            this._updateData();
          }
        });
      });
    </script>
  </dom-module>
</body>

Check out the interactive demo here

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

Although XPath works in Chrome, it is not compatible with Selenium

My current task involves finding an element based on its content that includes single quotes. I have successfully achieved this using vanilla JS as shown below: singleQuotes = document.evaluate("//div[contains(text(), \"'quotes'\")]" ...

Retrieve the width of an element once the browser has finalized its dimensions

I am facing an issue with centering a pop-up box perfectly within the window using CSS properties. The code for the pop-up box styling is as follows: #pop_up { position: fixed; display: inline-block; border: 2px solid green; box-shadow: 0p ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

Using Object Value as Variable instead of String in JavaScript/React

When working with React & JavaScript, I am storing an input name as a string in an object: window.ObjectOne = { ObjectOneKey: "MyInputName", } The input name can be an object path like "Object.FirstName" or a variable name "MyVariableName" What I am at ...

Tips for incorporating Emoji into a messaging platform similar to SendBird (non-native, web-based application)

Hey everyone! I'm currently working on a project that involves integrating the "SendBird" messaging service. I've successfully implemented all the basic functions, but now I want to incorporate Emoji for better user experience. I'm feeling a ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

Can an HTML DOM object be converted to a JSON string using JSON.stringify in JavaScript?

Trying to fetch an external HTML file and convert its body content into a string has been giving me unexpected results. Is there a way to achieve this successfully? var xhr = new XMLHttpRequest(); function loadFile(){ xhr.open("GET", 'index.html ...

Data is not returned following an echoed Ajax call

The issue I am currently facing is that the ajax call is successfully updating the record but it is not returning the string of echo as expected. This script was previously functioning without any problems, however, after some sort of upgrade, it seems to ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

Is it possible to develop a reversed version of AJAX-IE? I am looking for this specific type of functionality

I've developed a web application that functions as a calendar with multiple tabs at the top. Currently, these tabs lead to new pages so that the user's back button works properly. Recently, I added a "help" box within the header that remains con ...

Iterate through the JSON response once the AJAX call is successful

Apologies for the duplication, this question was originally asked on Stack Overflow, but as a newcomer to this topic, I am seeking guidance on how to achieve it? Below is my AJAX call: $("#btnprocess").click(function () { $.ajax({ ...

Creating a line of functions pool in Javascript with a delay feature

Recently, I created a code snippet that simulates a function line. It involves calling functions such as fn1, delay, fn2, delay, and so on. The idea is to call a function, remove it from the line, have a short sleep, and repeat. However, I've encount ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

Error loading OBJ file in Three JS OBJLoader module

i'm having trouble importing an obj file using OBJLoader The obj file looks like this - Obj Image https://i.sstatic.net/HPdR8.png But when imported into Three.js, it looks like this - Obj in Three.js https://i.sstatic.net/CoSYz.png The obj file ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

"Search Functionality Failing to Perform as Intended Across Various Fields

I am working with 3 search fields (event_name, event_loc, event_date), and when only one of them is filled out, it should return just one table data entry instead of all. views.py def searchEvent(request): if request.is_ajax(): q_event_name = ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

Stopping the onkeypress event after altering focus

I have a form where my users are asking for the ability to move focus to the next field when the enter key is pressed, instead of submitting the form. To achieve this, I have implemented an onkeypress event handler on the text input field to change the foc ...