Encountered a JavaScript error while parsing the HTTP response

Currently, I am faced with the challenge of extracting and processing data from the www.skiddle.com API using Javascript:

$.ajax({
        url: 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
        type: "GET",
        success: function(response) {
        var list = [];
        $(response).find("results").each(function() {
        var el = $(this);
        var obj = {
                   "eventname": el.find("eventname").text(),
                   "imageurl" : el.find("imageurl").text(),
                  };
        list.push(obj);
        });

Upon examining the response, it appears to contain a results property with a single element within an array:

{error: 0, totalcount: "1", pagecount: 1, results: Array(1)}

However, despite this structure, when attempting to parse it using $(response).find("results"), no output is returned.

Answer №1

If you're confident that your response will include a property called result array, you can use response.results to access the array.

success: function(response) {

  $.each(response.results,function(indx,item){
       console.log(item);
       var obj = {  
                    eventname: item.eventname,
                    imageurl : item.imageurl
                 };
      list.push(obj);
  });

}

Assuming list has been defined as an array earlier.

If you know there is only one item in the array, you don't need a loop – you can simply access it using response.results[0]

success: function(response) {
  if (response.results.length>0) {
     var obj = { eventName: response.results[0].eventname,
                 imageurl : response.results[0].imageurl };
     list.push(obj);
  }
}

I've also observed that your new object has the same property names as the object being iterated through. In such cases, you can directly add the same object

 list.push(response.results[0]);

This will add the first item as it is. Any additional properties in the item will also be included in the added item in the list.

Answer №2

Instead of trying to parse the response as XML, make sure you are treating it properly as JSON.

To retrieve the desired list, simply include the following code snippet:

success: function(response) {
    var list = (response.results || []).map(function(result) {
        return {  
            eventname: result.eventname,
            imageurl : result.imageurl
        };
    });
}

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 increasing the height of a ghost image for an HTML draggable element

I'm currently working on a scheduling calendar that allows users to book time slots and easily drag and drop them to adjust the time. Each time slot is represented as a draggable HTML element. However, I've noticed a problem where the preview ima ...

Error occurs in Selenium when a button is clicked: ".MoveTargetOutOfBoundsException"

In my project using Safari and Python with Selenium, I encountered an issue while trying to create a Python Selenium program that clicks on a 'confirm' button within an iframe. Despite the button and the iframe being in the viewport, the program ...

Tips for incorporating the "build" directory into the Travis-CI build process and deployment of an npm module

Currently, I am working with a Typescript module that has a directory ./src And I also have travis-ci set up for the project. language: node_js node_js: - 5.1.0 install: - npm install - npm install -g mocha - npm install -g gulp - npm install -g tsd - ...

The ion-slide-box does not function properly the first time the HTML page is loaded

Upon loading the page, my ion-slide-box does not function correctly. However, if I refresh the page, it works as expected. I have tried referring to some links but have been unable to resolve this issue on my own. Any assistance would be greatly appreciate ...

execute bower install for the specified bower.json file

Let's say my current working directory is c:\foo\ while the script is running. I want to execute bower from there for the c:\foo\bar\bower.json file. This can be done in npm by using npm install --prefix c:\foo\bar. ...

What is the best way to eliminate a specific item from an array of objects within a function?

1. When utilizing the findUnsubmitted function with an array of submission objects, a specified date, and student names array, the function returns the names of students who have not completed any quiz on that particular date. If the findUnsubmitted featu ...

Access the values within an array located inside a data object by utilizing ng Repeat function

Attempting to utilize ng repeat for extracting values from an array. Below is the HTML code: <ion-list ng-repeat="item in locationresult"> <ion-item > <ion-checkbox ng-repeat="innerItem in item.loc[$index]"> ...

Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link: https://codepen.io/queflojera/pen/RwwLbEY?editors=1010 At the moment, the carousel functions smoothly on opera, chrome, edge ...

Import .obj files from user's personal computer using THREE.js

As we all know, HTML5 includes the powerful FileReader API which allows users to load local files based on their selection. However, I am interested in displaying the .obj model that the users have selected. Given that FileReader can only interpret thing ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Utilizing a captured group from a regular expression as a key in replacing a string

Looking for help understanding the behavior displayed in this NodeJS 12 console code snippet. I'm attempting to replace a portion of a string with the result from a capture group. While it does work, using that capture group result as a key in an obje ...

Using Angular Material 6 with Mat-Chip-List: when two mat-chip-list declarations are linked to identical data sources

Experimenting with Angular 6 and Angular Material, I am attempting to create 2 Auto-complete Chip Lists using distinct data sources. The modification of the previous example can be seen here: https://material.angular.io/components/chips/overview Yet, it a ...

I am interested in retrieving document information from Firebase

/* eslint-disable indent */ import React, { useEffect, useState } from 'react'; import { Alert, } from 'react-native'; import firebase from 'firebase'; // import { useIsFocused } from '@react-navigation/native'; im ...

Tips on updating an HTML page following the receipt of a CURL request by a PHP script

I am currently developing a unique login system with customized requirements. The HTML form will submit data to a PHP script using AJAX, which will then forward the information to another PHP script for processing through CURL. After some time has passed ...

I'm struggling to grasp this node js code because there doesn't seem to be any server.emit. Can anyone shed some light on why that

I'm struggling to grasp the concept behind this code. My confusion lies in line 8 (server.on). After using server.on, it is supposed to listen for an event, but why isn't server.emit being used? What exactly is handling the functionality of se ...

Using TypeScript to Make SOAP Requests

I am attempting to execute a SOAP request using TypeScript, but I'm encountering an issue when compiling the code with "tsc myfile.ts". Here is the code snippet: import Soap from 'soap'; function soapClientServer(){ const url ...

Ajax - unauthorized invocation issue

I am currently working with the following function: function createSkillCard(attributeData,name) { $.ajax({ type: "POST", url: "/Skillcard/create", dataType: 'json', data: { request: 'aja ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

What steps should I take to configure a test environment specifically for conducting tests with selenium and phantomjs?

I am in the process of setting up my environment for headless testing using Selenium and PhantomJS. Getting PhantomJS Ready: To start, I created a folder named c:/phantomjs and downloaded all the necessary PhantomJS script files into it. Next, I set up a ...

What is the method for incorporating an infowindow into a data layer using Google Maps API?

I seem to be having trouble with incorporating an info window into a data layer containing information from a geojson link. Despite my efforts, the info window does not appear as intended in the code snippet below. To address this issue, I followed the in ...