Refreshing the content using AJAX and sending a request to update

I am currently working on a project where I need to fetch data through an ajax call and then send that data back using ajax as well.
Here is the javascript code:

setInterval (function ()
    {
      var xmlhttp = new XMLHttpRequest();
      var content = "data=1";
      xmlhttp.onreadystatechange = function()
        {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
              {
                content = "data=" + xmlhttp.responseText;
                alert (xmlhttp.responseText);
              }
        }
      xmlhttp.open("POST" , "execute-page.php" , true);
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send(content);
    },5000);

However, I am facing an issue where it keeps sending the old content. How can I update the content variable with the ajax response text?

Answer №1

Make sure to move the line var content = "data=1"; outside of the function:

var content = "data=1";
setInterval (function ()
    {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function()
        {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
              {
                content = "data=" + xmlhttp.responseText;
                alert (xmlhttp.responseText);
              }
        }
      xmlhttp.open("POST" , "execute-page.php" , true);
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send(content);
    },5000);

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 smoothly transitioning elements to a visible state with a Fadein effect

I have been using a code snippet I found to fade in elements with the class "hideme" as I scroll to them. However, the elements only fade in when they are fully visible. Is there a way to modify the code so that they fade in as soon as they appear in the b ...

Issue with Material-ui autocomplete not updating its displayed value according to the value prop

My task involved creating multiple rows, each containing a searchable Autocomplete dropdown populated through an API, along with other fields. Everything was functioning perfectly until I encountered an issue when deleting a row from the middle. After dele ...

Trouble retrieving information from database with ajax implementation

i am struggling with the following code: connecting to a database <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $conn = new mysqli("localhost", "root", "", "jquery"); if ($conn->connect_error) { die("Connectio ...

Error: No @Directive annotation was found on the ChartComponent for Highcharts in Angular 2

I'm having trouble integrating Highcharts for Angular 2 into my project. After adding the CHART_DIRECTIVES to the directives array in @Component, I encountered the following error in my browser console: EXCEPTION: Error: Uncaught (in promise): No ...

The image we downloaded seems to indicate that our system does not support this particular file format

I have a static HTML file that is hosted on Netlify. Here is the URL: After successfully downloading the images, when I try to open them I receive an error message stating "it appears that we don't support this file format". I am unsure why this is ...

jQuery UI - Inconsistent results with multiple autocomplete feature

I am facing an issue with the tags.json file provided below: [ {"label" : "Aragorn"}, {"label" : "Arwen"}, {"label" : "Bilbo Baggins"}, {"label" : "Boromir"} ] In addition, I have a JavaScript code snippet (which ...

Verify that the password is entered correctly in Angular2

My Angular2 form looks like this: this.registerForm = formBuilder.group({ 'name': ['', Validators.required], 'email': ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+&bso ...

Implement a feature in Vue.js using vee-validate to dynamically add an element when a form field is validated

When using vee-validate, a Vue.js plugin for form validation, my goal is to display an image after the input field has been validated. I attempted to achieve this using v-show="!errors.has('fname')". However, the issue arises when the image appea ...

Display different modal based on URL using jQuery

Is there a way to display a specific modal based on the URL? I'm utilizing Bootstrap as my responsive framework. Currently, I have multiple modals, but for simplicity let's focus on two: privilege_10 privilege_11 These modals are triggered u ...

Issue with the loss of scope in the Subscribe event causing the Clipboard Copy Event

Hey there, currently I am attempting to implement a text copying feature in Angular 2. I have a function that executes when a button is pressed, fetching data from the database and converting it into readable text, which is then automatically copied to the ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Issue with NG Style not binding to page as expected

I am currently working on creating a web page with two sections that can be horizontally slid back and forth to occupy different widths on the page. My idea was to monitor the width percentage of the draggable bar that separates the two panes/sections, and ...

Is it possible to simultaneously send a JSON object and render a template using NodeJS and AngularJS?

I'm currently facing issues with my API setup using NodeJS, ExpressJS Routing, and AngularJS. My goal is to render a template (ejs) while also sending a JSON object simultaneously. In the index.js file within my routes folder, I have the following s ...

Function for querying database is not executing in an asynchronous manner

After setting up a function in my node server to handle querying the database and returning results, I found that using async await could help streamline the process throughout my routes. This way, I wouldn't end up with nested queries within one anot ...

Implementing beforeSend and complete in all instances of ajaxForm throughout the entire application as a universal

Is there a way to use the beforeSend and complete functions on all ajaxForms within a project without having to repeatedly insert the same code throughout the entire project? I have managed to achieve this by adding the following code for each form indivi ...

The AJAX function consistently delivers HTML content in its response upon successful execution

Attempting to utilize JQuery AJAX function in a Laravel 5.8 project to send a GET request to a project route URL, I consistently receive a 200 status response indicating successful execution. However, each time the function returns the current view HTML in ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Material UI filterSelectedOptions not functioning properly on initial search with multiple autocomplete

When I utilize the filterSelectedOptions prop in my autocomplete feature, it functions as intended when using a pre-defined chip. Check out image1 for an example: image1 However, when a brand new typed option is entered, it ends up duplicating multiple ti ...

The attempt to bring in the model using `require` has resulted in an error. The `require` method used here, in combination with `path.join`, does

As a beginner in web development, I have been working on a project using MySQL, Node.js with Express. However, I am encountering a TypeError issue when using Sequelize. Can anyone kindly explain this to me and assist me in finding a solution? "seque ...

Utilizing arrow keys as a means of setting focus (HTML & JavaScript)

Is it possible to program the left arrow key to function like the tab button (moving focus to the next focusable item) and the right arrow key to function as a shift+tab (moving focus to the previous focusable item)? I've made some progress with the ...