Unspecified content was received in the AJAX response

These are the two posts I am currently following:

  1. Ajax responseText comes back as undefined
  2. Can't return xmlhttp.responseText?

Although I have implemented the code in the same way, I am encountering:

"undefined is not a function" error message

whenever I use the callback() function in my code.

Below is the snippet of my code:

function articleLinkClickAction(guid,callback){

    var host = window.location.hostname;
    var action = 'http://localhost:7070/assets/find';
    var url = action + '?listOfGUID=' + guid.nodeValue;
    console.log("URL "+url);
    xmlhttp = getAjaxInstance();
    xmlhttp.onreadystatechange = function() 
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var response = JSON.parse(xmlhttp.responseText);
            console.log(response);
            console.log(xmlhttp.responseText);
            callback(null, xmlhttp.responseText);// this is line causing error
        }
        else{
            callback(xmlhttp.statusText);// this is line causing error
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
}

Below is the code snippet where I am calling the above function:

var anchors =  document.getElementsByTagName("a");
        var result = '';
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];

            var guid = anchor.attributes.getNamedItem('GUID');
            if(guid)
            {
                articleLinkClickAction(guid,function(err, response) { // pass an anonymous function
                    if (err) {
                        return "";

                    } else {
                        var res =  response;
                        html = new EJS({url:'http://' + host + ':1010/OtherDomain/article-popup.ejs'}).render({price:res.content[i].price});
                        document.body.innerHTML += html;
                    } 
                });
            }
        }

Answer №1

Your current code is using a single global variable for the xmlhttp object, which causes issues when trying to run multiple ajax calls simultaneously as each call will overwrite the previous one. To fix this, it is recommended to add 'var' in front of the xmlhttp declaration to make it a local variable within your function, allowing each ajax request to have its own separate state.

function articleLinkClickAction(guid,callback){
    var host = window.location.hostname;
    var action = 'http://localhost:7070/assets/find';
    var url = action + '?listOfGUID=' + guid.nodeValue;
    console.log("URL "+url);

    // add var in front of xmlhttp here to make it a local variable
    var xmlhttp = getAjaxInstance();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var response = JSON.parse(xmlhttp.responseText);
            console.log(response);
            console.log(xmlhttp.responseText);
            callback(null, xmlhttp.responseText);
        }
        else {
            callback(xmlhttp.statusText);
        }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
}

It is also recommended to use Javascript's strict mode to avoid accidental global variables and ensure all variables are explicitly declared as local or global. Additionally, another issue is identified in your code where altering the inner HTML of the body during an iteration can cause dynamic changes to the HTMLCollection obtained from document.getElementsByTagName("a"). To address this, a new approach of creating and appending elements is suggested instead of altering the inner HTML directly.


Instead of using document.body.innerHTML += html, consider the following updated code block:

(function() {
    var anchors = Array.prototype.slice.call(document.getElementsByTagName("a"));
    var result = '';

    for (var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        var guid = anchor.attributes.getNamedItem('GUID');

        if (guid) {
            articleLinkClickAction(guid, function (err, response) {
                if (err) {
                    console.log('error : ' + err);
                } else {
                    var res = response;
                    var html = new EJS({
                        url: 'http://' + host + ':1010/OtherDomain/article-popup.ejs'
                    }).render({
                        price: res.content[i].price
                    });

                    var div = document.createElement("div");
                    div.innerHTML = html;
                    document.body.appendChild(html);
                }
            });
        }
    }
})();

These changes address the earlier issues and ensure a more efficient and effective operation of your code.

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 concealing the background HDR map display in three.js without compromising the HDRI's contribution to the lighting effects

In my code, I have implemented the following example: Source: https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_gltf.html#L53 While HDRI lighting works perfectly, I am struggling to hide the HDR map from the background. Is there a way ...

Instructions for transforming DOM information into a JSON format

I have multiple inputs within my document, as shown in the code snippet below. My goal is to create a string or JSON object using the input names and values. var arr= []; $('ul li input').each(function(){ let name = $(this).attr(' ...

Creating visual content on Canvas using JavaScript

Having an issue with stacking multiple images on separate Canvas layers, and they're not drawing on the canvas. Can anyone help me figure out what I'm missing? Thanks CSS .positionCanvas{ position: absolute; left:0; righ ...

Top technique for creating an XMLHttpRequest instance

Which technique is recommended for generating an XMLHttpRequest object? The method should be compatible with all modern browsers. ...

Content within iframe is failing to load correctly on both Firefox and Internet Explorer browsers

On my website, I have 4 iframes embedded in 4 different tabs. I've noticed that the content is being cropped when viewed on Firefox, but it loads properly when using Chrome. Strangely, if I manually reload the iframe, the content displays correctly. T ...

What is the reason behind Firefox failing to display a linear gradient when the background-size values are more than 255px?

I am working on creating a grid overlay using an absolutely positioned non-interactive div. My approach involves using the repeating-linear-gradient property as suggested by others for this purpose. The functionality works smoothly in Chrome, but I seem to ...

Execute PHP function through Ajax

I have a button in my HTML code that looks like this: <button class="uk-button uk-button-primary uk-modal-close confirm-rules" type="button" onclick="sendStatus('accept_rules')">Rozumiem</button> When I click on the button, I want t ...

Is it possible to generate grid options dynamically for various tables within AngularJS using ui-grid?

I have developed a service for ui-grid table functionality. Currently, I am able to use this service on a single page but now I want to extend its usage to multiple pages, each with different table data. How can I pass grid options and JSON data for multip ...

Corrupted Excel file after downloading using the axios library in Vue.js

I'm having trouble downloading an Excel file using axios. Below is the code I have tried: axios.post(backendURL + 'api/client?file_name='+file_name,params, { file_name: file_name }, { responseType: 'blob' ...

Transmitting an XML document object through a POST request to a PHP script

Currently utilizing Javascript, I'm attempting to send(firstrequest.responseXML) to a PHP script and haven't been able to find any helpful resources on how to accomplish this. Here's what I've tried: var http = new XMLHttpRequest(); va ...

Expand Menu Options (jQuery)

Currently facing a jQuery problem that I can't seem to figure out. I've set up a menu with submenu elements and want to toggle the content height by clicking on menu items. The issue arises when clicking on another item causes the content to coll ...

Implementing OutlinePass from Three.js in React

I am attempting to implement the Post-processing Outline Thee.js example in a React environment with server-side rendering. The challenge I am facing revolves around lines 47 and 280 in the example: <script src="js/postprocessing/OutlinePass.js">< ...

Having trouble displaying a JSON response on an HTML page with AJAX

I've written an AJAX function that goes like this: function ajx(){ var ajaxRequest; // This variable makes Ajax possible! try{ // Works in Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Exp ...

Having trouble retrieving user data that is being passed as a context value using React's useContext

Currently, I am integrating Google login into my React application and facing an issue with passing the response data from Google login (i.e. user data) to other React components using the useContext hook. Unfortunately, I am unable to retrieve the user da ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

Angular.js dynamically changing ng-class based on long-polling updates to a monitored variable

Currently utilizing angular.js for my project. I am implementing long polling with a server and would like to dynamically update an element in the view, specifically one with a class of 'updated', whenever the value of build_tag is incremented. ...

Guide to automatically inserting text into an html form and submitting it without manual intervention

Currently, I am in the process of a project where my main goal is to design an HTML form for submitting replies. One interesting feature I want to include is an option for users who are feeling lazy to simply click on "auto-generate comment", which will ...

CSS: Concealing a separate div

I am working with a parent div in my code that has 2 child divs. I am hoping to find a way to hide the second child when hovering over the first child, using only CSS or JavaScript. Take a look at my Fiddle here <div class="parrent"> <div id ...

Selecting and Uploading Multiple Files in Internet Explorer (less than version 9)

I have been struggling with selecting and uploading multiple files at once to the server. Here is the code I am currently using: <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data" name="myForm"> <l ...

Interactive mobile navigation featuring clickable elements within dropdown menus

I recently implemented a mobile nav menu based on instructions from a YouTube tutorial that I found here. Everything was working perfectly until I encountered an issue on the 'reviews list' page. The dropdown in the mobile nav is supposed to be ...