Issue with HTML displaying undefined from API response instead of the expected value

I can't figure out why this issue is occurring, but here is the code I'm working with:

<div id="list">

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script>
        $(document).ready(function(){
          $.ajax({
            type:"get",
            url:"https://cors-anywhere.herokuapp.com/http://41.78.37.222/dev/api.php?action=list",
            success: function(data){
            result="";
            for(i in data){
            result+="MAKE: "+data[i].make+" // TYPE: "+data[i].type+"<br>";
            }
            $("#list").html(result);
            }
          });
        });
    </script>

Please note that I am using before my API URL to bypass CORS Policy error (temporarily). The API URL I'm using is

When I run the code, it currently shows:

MAKE: undefined // TYPE: undefined

instead of something like:

MAKE: BMW 320i (E90) 2009 Facelift // TYPE: Standard

Answer №1

The issue is centered around the variable data. It was assumed to be an object when it is actually a string.

By using for(i in data), the code loops through each character in the string.

To fix this problem, the string stored in data should be converted into an object by utilizing JSON.parse(). This will allow for enumeration of the object just as before, as demonstrated in the updated snippet below:

$(document).ready(function(){
  $.ajax({
    type:"get",
    url:"https://cors-anywhere.herokuapp.com/http://41.78.37.222/dev/api.php?action=list",
    success: function(data){
    result="";
    dataObj = JSON.parse(data);
    for (i in dataObj) {
      item = dataObj[i];
      result+="MAKE: "+item.make+" // TYPE: "+item.type+"<br>";
    }
    $("#list").html(result);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">

</div>

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

Retrieve the information located within the error section of an Ajax request

When sending an ajax request to a Django view, I am including data in the response based on certain logic. return JsonResponse(content={ "Message": "user is not present.", },status=400) This response falls under the error section ...

Understanding the unpredictability of A-Sync in Node.js/Express: Why does it appear to operate in a non-linear fashion?

Recently, I delved into the world of Node.js/Express and encountered asynchronous calls that must complete before moving on. My code features three different endpoints that need to be hit. Considering the asynchronous nature, I attempted to structure my c ...

Difficulties encountered in implementing functions and accessing the base in the Bookshelf model base extension

I've recently started learning Bookshelf.js. I'm utilizing bookshelf-modelbase for models, and also including password-hash-and-salt to facilitate password storage in the database. Currently, my focus is on implementing a function to set a user& ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

Tips for showcasing a collection of items in a React application using data from a database

My goal is to display a list of items from a database, filtered by the Id of the currently logged-in account on the application. To achieve this, I attempted to use a previous state with the account information and fetch only those items using the id in t ...

Accessing the id within both objects is proving to be a challenge for me

I'm facing an issue with accessing and posting values of the id within Position and Department in Angular. It seems like the id is not being accessed correctly. addEmployee.model.ts export class AddEmployee { Position: { id: string; }; De ...

Displaying various image previews in separate divs from user input

Is there a way to allow users to upload multiple images from their computer and have them displayed in separate divs on the webpage? I want users to be able to select images using input fields and then see the uploaded images in different div containers. ...

Enhancing Element Generation and Data Association through jQuery

Currently, I am seeking a more streamlined approach to generate DOM alterations and update the object within .data(). At the moment, data is being supplied in an array of objects. I construct strings piecemeal, appending them to the table body, and affixi ...

Having Trouble with Angular CLI Installation

Encountering an error during the installation process of Angular CLI. Any assistance would be greatly appreciated. C:\Users\A737539>npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2d22270 ...

The magic of jQuery when chaining AJAX callback functions

I have a centralized ajaxSuccess callback function that needs to initialize components from various AJAX calls across the project. Here is an example: $(document).ajaxSuccess(function (response, status, xhr) { initComponents(); }); For module-level a ...

Exploring the capabilities of jQuery by creating custom functions utilizing the .data method and HTML5 data

My goal is to dynamically add a new "app" to my "AppList" when a button is clicked. Javascript Solution: $(".appCreate" ).click(createNewApp); function createNewApp() { var facebookTemplate = $("#facebook-template").html(); var appName = $(this ...

Copying information from one website and transferring it to another website

To verify a user's authentication, I first collect their username and check it against the database to determine their authentication method. Depending on the authentication method, I then provide them with the appropriate login window to access their ...

Ways to resolve cross-domain problems without the utilization of PHP

I have successfully implemented the code below, however I used demo.php to address the cross domain issue. How can I achieve this without using PHP, as the client prefers not to use it? $('#basic-search').submit(function(el){ var sear ...

Extract the element from one array that is not present in another array

I am attempting to extract the values from arrayOne that do not appear in both groups within arrayTwo. In the example below, I am looking to identify b and d for group1 and a and b for group2. arrayOne = ['a','b','c',' ...

Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below: +------+---------+----+----+----+----+-------+----------+ | Year | Subject | A | B | C | F | Total | PassRate | +------+---------+----+----+----+----+-------+----------+ | 2015 | Maths ...

Internet Explorer versions 9 and 10 do not support the CSS property "pointer-events: none"

In Firefox, the CSS property pointer-events: none; functions properly. However, it does not work in Internet Explorer 9-10. Are there any alternative approaches to replicate the functionality of this property in IE? Any suggestions? ...

Struggling to retrieve external JSON data with JSONP

My goal is to fetch a remote JSON file using jQuery 1.11.1. The server does support jsonp, and I am able to download the .jsonp file by simply entering the call address with "?callback=foo" in a browser. However, when attempting to retrieve it via ajax, i ...

Making a cross-origin request to an external API using the HTTPS protocol

Trying to fetch JSON data from this URL: Despite attempting CORS, the request failed. Below is the code I used based on a template: function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { xhr.open ...

Firebase Cloud Functions streamline lengthy tasks by avoiding the risk of hitting a time threshold

Upon uploading videos to firebase storage, I am faced with the task of transcoding webm files to mp4 format. While I have a functional code demo available here, the issue arises when dealing with large video files. The conversion process often exceeds the ...

Utilizing the Bootstrap has-error class when implementing data annotations for error handling in your code

Is there a way to apply Bootstrap's has-error css class to a container div when a form error occurs and data annotations are being used? In the viewmodel class, I have the following property: [Display(Name = "First Name")] [Required(ErrorMessage = " ...