Retrieve JSON information via AJAX

Consider the following JavaScript AJAX request:

 $.ajax({
        type: "POST",
        url: "/myurl",
        async: false,
        data: JSON.stringify({}),
        contentType: "application/json",
        complete: function (data) {
                var results = data["responseText"];
                alert(results)
        },
        error: function () {
              alert("Error")
        }
 });

The JSON response received is as follows:

{"jsonrpc": "2.0", "id": null, "result": "{\"ids\": [{\"id\": 1, \"name\": \"Messi\"}, {\"id\": 2, \"name\": \"Ronaldo\"}]}"}

I want to display the data in a div as shown below. How can I achieve this?

1 Messi

2 Ronaldo

Answer №1

Extract the ids data from your Ajax response, iterate through it, and build the desired HTML structure using that information. Finally, inject this HTML content into your web page.

/*
            $.ajax({
                type: "POST",
                url: "/myurl",
                async: false,
                data: JSON.stringify({}),
                contentType: "application/json",
                complete: function(data) {
                    var response = data["responseText"];
                    var insertDatas = JSON.parse(response.result);
                    var htmlString = "";
                    insertDatas.ids.forEach(function(item) {
                        htmlString += '<li>' + item.name + '</li>';
                    });//forEach()

                    $("#players-list").html(htmlString);
                },
                error: function() {
                    alert("Error")
                }
            });
        */

        var response = {
            "jsonrpc": "2.0",
            "id": null,
            "result": {
                "ids": [
                    {"id": 1, "name": "Messi"},
                    {"id": 2, "name": "Ronaldo"}
                ]
            }
        };

        var htmlString = "";
        response.result.ids.forEach(function(item) {
            htmlString += '<li>' + item.name + '</li>';
        });//forEach()

        $("#players-list").html(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ol id="players-list"></ol>

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

Unable to isolate segments of a string

Looking for a way to extract two different IDs from the following string: SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: using Javascript. The regular expression being used is : ^SPList\:(?:[0-9A-Za-z\-]+ ...

Detecting Duplicates in an Angular JS Repeater and Handling the Not Allowed Exception

I am working on a task where I need to ensure that the object being added to an array of objects is not already present in a temporary array of objects. While using AngularJS, I encountered an error stating "Duplicates in a repeater are not allowed." This ...

What is the best method for distributing this array object?

I am faced with the task of spreading the following object: const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }]; I want to spread this array object and achieve the following format: form:{ ...

Querying JSON Data in an Ajax Request: A Simple Guide

I have a data file in json format that looks like this: {"markers":[ { "latitude":11.58655, "longitude":122.755402, "type":"A"}, { "latitude":11.00698, "longitude":124.612801, "type":"B"}, { "latitude":10.30723, "longitude":123.898399, "type": ...

The appearance of the upload button in React using Material-UI seems off

After following the MUI document on React Button upload, I noticed that the UI results were different than expected. Instead of just showing the button UI, there was an additional UI element present. By adding the sx={{display:'none'}} property, ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...

Interactive div containing elements that cannot be clicked

http://codepen.io/anon/pen/zxoYBN To demonstrate my issue, I created a small example where there is a link button within a div that toggles another div when clicked. However, I want the link button to not trigger the toggle event and be excluded from the ...

Tips for avoiding Netlify's error treatment of warnings due to process.env.CI being set to true

Recently, I encountered an issue with deploying new projects on Netlify. After reviewing the logs, I noticed a message that had never appeared during previous successful deployments: The build failed while treating warnings as errors due to process.env.CI ...

Is it possible to retrieve real-time scores of the players from espncricinfo through Node.js with the help of Cheerio parser?

Currently, I am facing an issue with retrieving live scores of individual players from espncricinfo. Despite my efforts, I have not been successful in fetching this data. Although some data is being retrieved dynamically, the scores are not showing up. Th ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

What is the best way to structure JSON data in JavaScript in order to effectively utilize a service?

I am attempting to connect to a service and have confirmed the correct connection, but I am encountering an error. I suspect that the JSON format may be incorrect. ERROR: net::ERR_ABORTED 500 (Internal Server Error). The technology being used is Jquery A ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...

The functionality of $.ajax is not compatible with Internet Explorer 8

I've been attempting to make my webpage function properly in IE, but I'm having issues with this code. It's not displaying "Fooo!" as a paragraph, nothing appears. However, it works perfectly fine in FF without any problems; <script> ...

The toggle checkbox feature in AngularJS seems to be malfunctioning as it is constantly stuck in the "off"

I am trying to display the on and off status based on a scope variable. However, it always shows as off, even when it should be on or checked. In the console window, it shows as checked, but on the toggle button it displays as off Here is the HTML code: ...

Pressing the back button in Chrome may result in the use of a cached version

Whenever I send an ajax request and update the page's content while also updating the history state, the server uses the X-Requested-With header to determine whether to send the full page or just the specific content. However, it appears that Chrome h ...

Ionic 3 Plugin for Handling HTTP Requests

I am facing an issue while trying to send a POST request using the HTTP Cordova plugin. The JSON data sent to the server is not being formatted correctly (missing JSON brackets). Can someone assist me with this problem? Here is the import statement: impo ...

What is the best way to ensure that a mongoose .exec() callback has completed before checking the response object in express?

I am currently developing an application that utilizes Express, Mongoose, and Jest for testing. In order to test my application, I have set up a mongodb in local memory for testing purposes. However, I am facing an issue in some of my tests where the callb ...

The load event in React's iframe is failing to fire after the src attribute is modified using state

In the process of creating a registration form for a React application, we encountered the need to incorporate an HTML legal agreement as an iframe. This legal document is available in various languages, one of which can be selected using a drop-down menu; ...