Struggling to convert a JSON file into a TableView within a JavaScript application developed with Appcelerator

Trying to display a JSON file in a table using JavaScript and Appcelerator is proving to be quite a challenge. The output appears as an empty table when compiled to an example page. As someone relatively new to JavaScript and JSON, I'm seeking guidance on any potential errors in logic or syntax. Here's the code:

// Setting background color without windows or tabs
Titanium.UI.setBackgroundColor('#000');

// Creating the window
var win1 = Titanium.UI.createWindow({  
    title:'Challenge Window',
    backgroundColor:'#fff',
});

// Storing image properties
var image = Titanium.UI.createImageView({
    image: "https://myavantiservices.files.wordpress.com/2015/02/helloworld.gif",
    height: 380,
    width: 380,
    center: 512,
    top: -50
});

var tableData;

// Parsing JSON file on load
var url = "https://www.sitepoint.com/twitter-json-example/";
var json;
var xhr = Ti.Network.createHTTPClient({
    onload: function() {
        json = JSON.parse(this.responseText);
        tableData = json;
    }
});

// Creating table and inserting JSON data
var table = Titanium.UI.createTableView({
    data: tableData,
    height: 480,
    width: 480,
    top: 256,
    left: 232
});

// Adding image to window and opening it
win1.add(image);
win1.add(table);
win1.open();

JSON data from the URL:

{"results":[
    {"text":"@twitterapi  https://code.google.com/archive/p/twitter-api/issues/353",
    "to_user_id":396524,
    "to_user":"TwitterAPI",
    "from_user":"jkoum",
    "metadata":{
       "result_type":"popular",
       "recent_retweets": 109
    },
    "id":1478555574,   
    "from_user_id":1833773,
    "iso_language_code":"nl",
    "source":"twitter< /a>",
    "profile_image_url":"http://s3.amazonaws.com/twitter_production/profile_images/118412707/2522215727_a5f07da155_b_normal.jpg",
    "created_at":"Wed, 08 Apr 2009 19:22:10 +0000"},

     ... truncated ...
],
"since_id":0,
"max_id":1480307926,
"refresh_url":"?since_id=1480307926&q=%40twitterapi",
"results_per_page":15,
"next_page":"?page=2&max_id=1480307926&q=%40twitterapi",
"completed_in":0.031704,
"page":1,
"query":"%40twitterapi"}
}

Answer №1

To ensure that everything relying on the JSON response is properly executed, make sure to move them inside the onload block. This will prevent the table from being constructed before tableData receives any data. Additionally, don't forget to actually send the xhr as well.

Once you have a valid URL returning the JSON data, you can implement the following code:

var url = "https://www.sitepoint.com/twitter-json-example/";
var json;
var xhr = Ti.Network.createHTTPClient({
    onload: function() {
        json = JSON.parse(this.responseText);
        tableData = json;

        var table = Titanium.UI.createTableView({
            data: tableData,
            height: 480,
            width: 480,
            top: 256,
            left: 232
        });

        win1.add(image);
        win1.add(table);
        win1.open();
    }
});
xhr.open("GET", url);
xhr.send();

Answer №2

Hey Jodo, it would be beneficial for you to take a look at the documentation for using HTTP Client and setting data on TableView in Appcelerator.

If you check out Titanium's Working With Remote Data guide, you'll find a helpful example.

The URL you're using seems to only return the HTML output of the website, and remember that you can't just set the data property on TableView without properly formatting your data like this:

[ {title: 'Apples'}, {title: 'Bananas'}, {title: 'Carrots'}, {title: 'Potatoes'} ];

Additionally, make sure that TableView's data property is being passed an array of Rows/Sections or a well-formatted dictionary. You can refer to the TableView Guide for more information.

We recommend taking some time to read through the documentation before diving into any new tasks. It will help you grasp concepts more effectively and ultimately save you time. :) Thank you!

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

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

There is an issue with Node/Express not accurately updating the data model

I recently went through a tutorial on creating a RESTful API with Node.js and MongoDB. While it worked well overall, I encountered a few issues. My Player model is as follows: var player = new mongoose.Schema({ name: String, email: String, score: String } ...

The output from the NodeJS storage module function

Attempting to implement Two-Factor Authentication in my initial NodeJS project, which serves as a learning tool for Node. While the function correctly retrieves values from data_url, when I assign it to a variable and return data_url, it returns 'und ...

Parsing JSON data containing multiple types of objects is made simple with JSON.net

Is there a way to deserialize a list of various objects using JSON.net? string myJson = "[{action: 'a1', target: 4},{action: 'a2', targets: [1,2,3], {action:'a3', text:'targets altered'}}]"; In this scenario, we ha ...

Incorporate an additional retrieve functionality in your asp.net web api

I'm brand new to the world of asp.net web api. I have a solid understanding of get(), put(), post() and delete(). For my application, I need to implement two additional get() methods. Here is an overview- public class StudentController : ApiControll ...

What is the method for showcasing a single Observable from an Array of Observables in Angular?

I am facing a challenge with displaying questions from an Observable-Array one by one. Currently, I can only display all the questions at once using *ngFor in my HTML. Here is my component code snippet: import { Component, OnInit } from '@angula ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...

What is the process for appending a file extension to a Next.js URL?

For instance, I am attempting to redirect the URL : https://example.com/data/publications to this : https://example.com/data/publications.json I made an attempt using Next.js redirection, but encountered difficulty when trying to add a string that does no ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

Tips on retaining label names for input boxes

Check out this Plunker example. I am trying to figure out how to keep labels on top of textboxes in this Plunker. Can anyone help me with that? <a class="btn btn-success btn-xs" data-nodrag ng-click="toggle(this)"><span class="glyphicon" ng-clas ...

Converting a unix timestamp to a Date in TypeScript - a comprehensive guide

To retrieve the unix timestamp of a Date in plain JavaScript and TypeScript, we can use this code snippet: let currentDate = new Date(); const unixTime = currentDate.valueOf(); Converting the unix timestamp back to a Date object in JavaScript is straight ...

Modify the fixed div's class when the user scrolls past a certain section

My page includes a fixed menu with various sections, each assigned a specific class name using data attributes (e.g. data-menu="black"). I want the fixed menu to change its class based on the section that is currently underneath it as the user scrolls. Y ...

Having trouble with PHP JSON response not functioning properly?

I'm currently working on an ajax update and I simply need a success or failure response to handle some front-end tasks. However, I am facing issues as it doesn't seem to be functioning properly. I'm fairly new to all of this. $('.delet ...

Retrieving data from a dynamic form using jQuery

Can someone assist me with the following issue: I have a dynamic module (generated by a PHP application) that includes input fields like this: <input type="text" class="attr" name="Input_0"/> <input type="text" class="attr" name="Input_1"/> ...

Is it possible to have Mobile WebKit store the click position?

I am in the process of developing a unique framework specifically designed for WebKit devices. One of the features I have implemented is a series of list views that activate a 'hover' class when users touch them. Below is the jQuery/JavaScript co ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...

The number range filter in ng-table is malfunctioning

what I am trying to accomplish My goal is to create a column that can accommodate two numbers in order to filter numeric data within a specific range for that column. While sorting, pagination, and filtering by 'contain text' are working correct ...

What is the layout of JqueryMobile web pages like?

When I need to pull pages, I use Asp.net MVC. The format of my pages is as follows: { Layout = ""; } <div data-role="page"> .... <script type="text/javascript"> $(document).one("pageinit", function () { . ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...