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 Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// A function to handle data received from the server
ajaxRequest.onreadystatechange = function(){
       // alert(ajaxRequest.readyState);
    if(ajaxRequest.readyState == 4){
                    //alert(ajaxRequest.responseText);

                    var res = ajaxRequest.responseText;


                    var a = JSON.parse(res);


                    var v1 = a[0];
                    var v2 = a[1];
                    var v3 = a[2];

                    //alert(v1);

                    document.getElementById('vara').value = v1;
                    document.getElementById('varb').value = v2;
                    document.getElementById('varc').value = v3;


    }
}

ajaxRequest.open("GET", "ajax.php", true);
ajaxRequest.send(null); }

The HTML with the id attributes looks like this:

<div id="vara"></div>
<div id="varb"></div>
<div id="varc"></div>

Here's the ajax.php file:

 <?php

$resp = array('man','cow','dog');

echo json_encode($resp);

?>

When I try to alert v1, v2, or v3, it shows man, cow, and dog respectively. But the values are not being displayed in the HTML. What could be the issue?

Answer №1

To enhance the functionality of your div elements, you are introducing a new attribute named 'value' since they currently lack one. The objective is to assign content to the innerHTML or innerText of each div:

document.getElementById('vara').innerHTML = v1;
document.getElementById('varb').innerHTML = v2;
document.getElementById('varc').innerHTML = v3;

Answer №2

document.getElementById('vara') will return an HTMLDivElement object, which lacks a value property.

To confirm this, you can use the following code snippet:

'value' in document.getElementById('vara'); //false

Instead, utilize the innerHTML property inherited from HTMLElement for HTMLDivElement.

'innerHTML' in document.getElementById('vara'); //true

Note that the value property is specifically for HTMLInputElement elements (such as <input type='text' />).

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

Update and renew dropdownlist data with the help of jQuery

I am looking to enhance my drop-down list by dynamically adding data without having to refresh the page. Although I can currently add and view the data, it requires a manual page refresh. I am seeking a solution using jQuery to accomplish this seamlessly ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Failure of jQuery Code Upon Successful Execution

I'm having an issue with my jQuery ajax code. It's functioning perfectly, but I can't seem to get it to change the class of the button that triggers the event when it is successful. The code under success: does not seem to be working as inte ...

Access my account on the one.com control panel using the identical login credentials

I am curious if it's possible to implement a login page on my website for customers and then seamlessly redirect them to the control panel on one.com without requiring them to re-enter their username and password? Visit the action page on one.com her ...

Using React to Calculate the Total Value of Child Components within the Parent Component

In this scenario, the parent component has access to the values of the child components but struggles to calculate the sum correctly. Instead of displaying the accurate total, it shows 0. https://i.sstatic.net/1etAx.png The expected behavior is for the To ...

The autocomplete feature in Codemirror seems to be failing specifically when writing JavaScript code

I am having trouble implementing the autocomplete feature in my JavaScript code editor using Codemirror. Can someone please help me figure out what I'm doing wrong? Here is the snippet of code : var editor = CodeMirror.fromTextArea(myTextarea, { ...

Using JavaScript to analyze and handle newlines, spaces, and the backslash character

Hello everyone, I'm hoping things are going well. I am currently working on removing newline and "\" characters from a string that I have after using JSON.stringify(). The string in question appears as follows: "[{\n \"id_profile&bs ...

What is the best way to adjust the maximum width of Reddit's embedded comment iframe?

Reddit provides a code that can be embedded to display their comments on a website, As an example: <div class="reddit-embed" data-embed-media="www.redditmedia.com" data-embed-parent="false" data-embed-live="false" data-embed-uuid="24a3e666-f855-4664 ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...

Warning issued by npm during compilation: The template string expression is unexpected as there should be no curly braces in the

Getting an npm warning during compiling (Unexpected template string expression no-template-curly-in-string) import React from 'react'; const Card = ({name, email, id }) => { return ( <div className='tc bg-light-green dib b ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

The ng-change event fails to trigger when the date change event is activated

Hey there, I'm new to working with AngularJS. I have a scenario where I want a method to be triggered when I change the date, opening a modal. However, when I use the ng-change event, the method is not called upon date change. If I switch to using ng- ...

How can we make the lines in the Highcharts force plot take up all the available width

Our design team has specifically requested that our stacked area charts fill 100% of the chart width, instead of stopping at the tick marks. To illustrate this, they have provided a mockup: View Mockup Currently, our chart does not extend to the full wid ...

Redirecting successfully after a 'delete' action in Express

When working from the client side, I am using jQuery to make an Ajax request of type "delete". On the server side, I am executing a res.redirect(URL) command. However, instead of redirecting as expected, the browser is making another delete request with ...

Using Jmeter to extract and verify an array of JSON objects

While working with Jmeter, I have encountered an issue when trying to extract data from a JSON object that contains an array of JSON objects. The extraction works perfectly fine for simple JSON objects, but fails when dealing with arrays. The result JSON ...

Export a list from R to Julia using JSON format

Imagine you have a list in R like this: x = list(a=1:3,b=8:20) You then save this to a JSON file on disk using the following code: library(jsonlite) cat(toJSON(x),file="f.json") Now, how can you read this JSON file using the Julia JSON package? Is it p ...

Implement the window.open functionality within a directive for optimal performance

I am attempting to activate the function $window.open(url, windowName, attributes); in my Angular application by using an ng-click event. I have created a directive and enclosed the window.open method within a trigger function that is connected to a butto ...

A script error occurs exclusively on dynamic routing in a static web page generated by NUXT

Currently working on a Nuxt.js website and encountering an issue. Initially, nuxt.config.js was set up as below to enable a headless CMS. export default { target: "static", ssr: true, generate: { async routes() { const pages = awa ...

Assign value to twig variable using JavaScript in Symfony version 3.4

Hello everyone, I am currently working on a form that is functioning well. However, I am facing an issue with setting the localization of a place manually using latitude and longitude values. To address this, I decided to create a map with a draggable mark ...

What could be causing my code to generate an error?

I'm encountering an error in module.js:339 where it throws an 'err' and I'm struggling to identify the exact cause or line of code that needs fixing. Any guidance on where to look would be greatly appreciated, as I seem to be searching ...