What is the best way to retrieve the response from an Ajax request?

I attempted to use this code snippet :

var xhttp = new XMLHttpRequest();

function activateComment(commentID, linkID)
{
    var data = "id="+encodeURIComponent(commentID);
    var endpoint = 'comments_handler.php'; 
    xhttp.open("POST", endpoint, true);
    xhttp.onreadystatechange = handleResponse(linkID);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.setRequestHeader("Content-length", data.length);
    xhttp.setRequestHeader("Connection", "close");
    xhttp.send(data);
}

function handleResponse(linkID)
{
    if(xhttp.readyState == 1)
    {
        document.getElementById("commentResult").innerHTML = 'loading ..';
    }
    else if(xhttp.readyState == 4)
    {
        var reply = xhttp.responseText;
        document.getElementById("commentResult").innerHTML = reply;
    }
}

Although the readyState == 1 condition successfully updates the content of the commentResult element, there seems to be an issue when readyState == 4 as no content is displayed in the same element.

If anyone has insight into what might be causing this problem, please share. Thank you!

Answer №1

Instead of assigning a ready state handler, you are currently calling the handleInfo function. Consider using the following code:

xmlHttp.onreadystatechange = function (){
    handleInfo(a_link_id);
};

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

Response is sent by Sequelize Foreach loop before data is updated

My goal is to retrieve all content and media from a post, then append it to a new post before sending it as a response for easier access to the data. The issue I'm encountering is that the response is being sent before the content and media are fetche ...

Ways to stop a JavaScript function from running during page loading

After clicking the submit button on my form, I want to send a confirmation post using the sendPostAjax() function before submitting the form to the payment provider. However, I'm facing an issue where the sendPostAjax() function is getting executed as ...

Anomaly observed in the deconstruction of Material UI table components

Utilizing the table component from the Material UI react components library, I encountered a need to incorporate custom behavior into the TableRow. To achieve this, my approach involved breaking down the table and planning to encapsulate it within my own ...

Interfacing Electron Frontend with Python Backend through seamless communication

Upon completing the development of a Python CLI app, it became apparent that creating an Electron frontend for better user interaction was necessary. What is the best way for the Electron app to communicate with the Python app when a user action occurs on ...

Having trouble loading json data after clicking in Angularjs?

I have been attempting to load JSON data upon clicking by utilizing this particular link. To replicate the process in my VS2012 environment, I included the following JavaScript and CSS files: <head> <link href="Content/style.css" rel="stylesheet ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

During the build process, Next.js encounters difficulty loading dynamic pages

My Next.js application is utilizing dynamic routes. While the dynamic routes function properly in development mode, I encounter a 404 error when deploying the built app to Netlify. https://i.stack.imgur.com/45NS3.png Here is my current code setup: In _ ...

When attempting to switch to node version 18.18.0 with NVM, Next.js raised a complaint about using a different node version (20.3.1) while starting a new project

Recently, I switched to node 18.18.0 to ensure compatibility with next.js dependencies. To streamline my setup, I uninstalled all other node versions except for this one. However, when trying to initiate a new next project using the command: npx <a hre ...

Displaying all items within a JSON variable using a for loop instead of just one item at a

Referring to my previously answered question (View Here) I've created a new JSON variable in PHP and passed it to a JavaScript variable. I have implemented a feature that displays the last read post by the user like this: [ //defined by var = book ...

Determine the status of a script in PHP by incorporating AJAX

I am having trouble with my file upload page in the application. I want to display "Uploading" while the file is uploading and then show "Processing" while the file is being processed. Eventually, after the script completes, my page should redirect to a sp ...

Prevent the selection of Single Origin and House Blend options once the user opts for Espresso

<td> <select class="type"> <option value="Espresso">Espresso</option> <option value="" class="">Cappuccino</option> <opti ...

The issue with updating state in React using dispatch within the same method is not working

Initially, I had a situation where the state was updating correctly with two separate methods (onClick). const sizesMeasureChoise = useSelector(getSizesMeasureChoise); const chooseMeasure = (measure) => { dispatch(setSizeMeasureChoise(measure)); ...

JQuery retrieves the text content without taking into account the class

I'm struggling with my code and encountering an issue fetching text while excluding the menu-list-count class which displays a value next to the text. Here's what I've attempted: var mailfolder = $(this).not('[class="menu-list-cou ...

How is it possible for a JavaScript variable sharing the same name as a div Id to automatically pass the div?

This is just ridiculous. Provided HTML <p id = "sampleText"></p> Javascript var sampleText = "Hello World!"; Execution console.log(sampleText); // prints <p id = "sampleText"></p> How is this even possible? I ...

Ways to conceal an element when it appears in the initial section of a page

I currently have a single-page website consisting of 4 sections which are not scrollable. To navigate between these sections, I have implemented a burger menu button with a fixed position to ensure it remains visible on all sections except the first one. ...

When utilizing row.add in AngularJS and jQuery DataTables, the ng-click function may not function as expected

As a newcomer to angularjs, I have successfully implemented the jQuery DataTable directive with angularJS. However, I am encountering an issue when trying to add a JavaScript function to "TR" dynamically using "ng-click", as it does not seem to be recogniz ...

Where exactly is the JSON data stored after I receive it through an AJAX request?

I am curious about where certain JSON data is stored when it is sent from the server to the client, especially when they reside in different directories. Currently, I am working on developing a simple API that sends JSON data from the server (port number: ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

How to delete a single item from an array using MongoDB

For my discord bot, I've implemented a purchasing system that adds items to the inventory array in mongoDB like this: data.Inventory[itemTobuy] ++; The stored format looks like this: pizza: 1 I also have a system in place where users can use items f ...

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...