The issue with the Ajax JSON Loader malfunctioning

Recently, I was working on creating a JavaScript AJAX loader for my blog. Unfortunately, it's not functioning as expected. Initially, everything was working fine until I decided to incorporate months into the parser and JSON file. From that point onward, the loader simply stopped loading.

Here is the snippet of JavaScript code:


firstTime = 1;
function ajax_get_json_for_main_page(a){

var counter = 0;
var results = document.getElementById("blogShow");

    var hr = new XMLHttpRequest();
    hr.open("GET", "articles/main.json", true);
    hr.setRequestHeader("Content-type", "application/json", true);
    hr.onreadystatechange = function() {
        var blog = new Array()
        var title = "";

        if(hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            for(var obj in data){
                for(var entry in data[obj])
                {
                    blog[counter] = "<h4>"+entry[obj].title+"</h4><p>"+entry[obj].post+"</p>"+"<hr />";
                    title += "<a onClick='willImpletmentlater(" + entry[obj] + ")" + "'>" + entry[obj].title + "</a><br /><br />"
                    counter = counter + 1;
                }

            }
            document.getElementById("big3").innerHTML = title;

            if(firstTime == 1)
            {
            results.innerHTML = blog[0]
            firstTime = 1000;
            }


            if(a == 1)
            {
                interval = setInterval(function(){blogShowAnimateInner(1, blog);}, 1);
            }
            if(a == 2)
            {
                interval = setInterval(function(){blogShowAnimateInner(2, blog);}, 1);
            }
            if(a == 3)
            {
                interval = setInterval(function(){blogShowAnimateInner(3, blog);}, 1);
            }
            if(a == 4)
            {
                interval = setInterval(function(){blogShowAnimateInner(4, blog);}, 1);  
            }


        }
    }   


hr.send(null);




}

Additionally, here is the JSON content being used:

 {
     "june": {
        "17": {
            "title": "Monday 17 of June 2012",
            "post": "the post taken out to save space."
        },
        "16": {
            "title": "Sunday 16 of June 2012",
            "post": "the post taken out to save space"
        },
        "15": {
            "title": "Saturday 15 of June 2012",
            "post": "the post taken out to save space"
        },
        "14": {
            "title": "Friday 14 of June 2012",
            "post": "the post taken out to save space"
        },
        "13": {
            "title": "Thursday 13 of June 2012",
            "post": "the post taken out to save space"
        },
        "12": {
            "title": "Wednesday 12 of June 2012",
            "post": "the post taken out to save space"
        },
        "11": {
            "title": "Tuesday 11 of June 2012",
            "post": "the post taken out to save space"
        },
        "10": {
            "title": "Monday 10 of June 2012",
            "post": " the post taken out to save space."
        }
    }

}    

Despite trying Jsfiddle, I realized they do not support AJAX loading. Thus, I couldn't find any hints there.

Edit: Now, the code seems to be working thanks to implementing changes suggested earlier.

A key part of the parse logic:

If(hr.readyState == 4 && hr.status == 200) { var data = JSON.parse(hr.responseText);

            var blog = [];
            var title = "";
            var counter = 0;

            for (var month in data) {
                var monthEntries = data[month];
                for (var i = 0; i < monthEntries.length; i++) {
                    var entry = monthEntries[i];
                    blog[counter] = "<h4>" + entry.title + "</h4><p>" + entry.post + "</p>" + "<hr />";
                    title += "<a onClick='willImpletmentlater(" + entry + ")" + "'>" + entry.title + "</a><br /><br />"
                    counter = counter + 1;
                }

            }

            console.log(blog);
            console.log(title);

            document.getElementById("big3").innerHTML = title;




            if(a == 1)
            {
                interval = setInterval(function(){blogShowAnimateInner(1, blog);}, 1);
            }
            if(a == 2)
            {
                interval = setInterval(function(){blogShowAnimateInner(2, blog);}, 1);
            }
            if(a == 3)
            {
                interval = setInterval(function(){blogShowAnimateInner(3, blog);}, 1);
            }
            if(a == 4)
            {
                interval = setInterval(function(){blogShowAnimateInner(4, blog);}, 1);  
            }


        }
    }   

Edit:
Everything appears to be functioning correctly

Edit:
Oddly enough, adding 'July' causes issues; specifically, the loader stops working. Quite strange, isn't it?

Answer №1

Ah, I understand your point now. The json response month object is structured as an object with key value pairs rather than an array. Since object keys do not have a set order of retrieval, you can modify the json response to achieve the desired order like this:

   {
     "june": [
        {
            "day": "17",
            "title": "Monday 17 of June 2012",
            "post": "the post taken out to save space."
        },
        {
            "day": "16", 
            "title": "Sunday 16 of June 2012",
            "post": "the post taken out to save space"
        },
        {
            "day": "15",
            "title": "Saturday 15 of June 2012",
            "post": "the post taken out to save space"
        },
        {
            "day":"14",
            "title": "Friday 14 of June 2012",
            "post": "the post taken out to save space"
        },
        {    "day": "13",
            "title": "Thursday 13 of June 2012",
            "post": "the post taken out to save space"
        },
        {    "day": "12",
            "title": "Wednesday 12 of June 2012",
            "post": "the post taken out to save space"
        }
    ]

}

The jsfiddle has been updated accordingly.

http://jsfiddle.net/ew44p/1/

Answer №2

It would be ideal to structure it in this way based on your json object.

for(var month in data){
        var monthEntries = data[month];
                    for(var day in monthEntries)
                    var entry = monthEntries[day];
                    {
                        blog[counter] = "<h4>"+entry[day].title+"</h4><p>"+entry[day].post+"</p>"+"<hr />";
                        title += "<a onClick='willImpletmentlater(" + entry[day] + ")" + "'>" + entry[day].title + "</a><br /><br />"
                        counter = counter + 1;
                    }

                }

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

Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve thi ...

Utilizing jQuery to access data stored locally

How can I retrieve and display all the values with key 'Task'? Below is the structure of the JSON data: {"Assignments":[{"AssignedBy":"537000","AssignedBy_FirstName":" JOHN","AssignedBy_LastName":"WANDER"}, {"AssignedBy":"537000","AssignedBy_Fir ...

jQuery Button State Toggler - Disabling and Enabling Buttons

I am trying to utilize jQuery to disable and enable a submit button based on the completeness of the user's input. I have been successful in disabling it, but unfortunately, I can't seem to figure out how to enable it afterwards. $('#submit ...

Troubleshooting angular radio input display issue caused by controller updates

When the page loads, my AngularJS controller.js initializes the scope model by fetching data from an AJAX response: services.InitializePage().then(function (response) { $scope.DataModel = response.data; Shortly after that, the model undergoes ...

Sending a JSON request using Swift 3

I am in need of posting JSON data that has the following structure: { "orders":[ {"id": 208, "quantity": 1 },{"id": 212, "quantity": 2},{"id": 202, "quantity": 5}, ...etc ],"HHStatus": "1 } Currently, I have a variable called orders : [ShoppingCart] = [] ...

Issue with JSON Encoding While Trying to Load Text Data from a Document

When attempting to open and load a JSON file in Python, the code ends up with a string filled with Unicode blocks between every character. It appears to be an encoding issue. Is there a simple way to resolve this problem? import json import io # read file ...

Exploring Alternative Methods for Serving Static HTML Files in an Express Server

Hey there, quick question for you. Let's say I have two static HTML files that I want to serve in Express - 'index.html' and 'contact.html'. I've been playing around with some basic Express code to get them served: const expr ...

Trouble with Directive - the watch function isn't functioning as expected

After spending countless hours and trying almost everything, I can't seem to get it to work... I have an Angular directive that calls another Angular directive. I need to handle events in the child directive. So my child directive looks like: ...

Use AngularJS to extract information from Wikipedia and display it

Just starting out with angularjs and attempting to pull data from Wikipedia to display on the front end. I managed to fetch the data using the php code below: $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&a ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

How can I make an image appear in React when it is

I am currently looking to incorporate an image every time I click incrementally. I attempted the solution below, which is in the commented-out section. BallonTest = () => { const [money, setMoney] = useState(0); const [bank, setBank] = useState(0); ...

Resource loading error: The server returned a 404 (Not Found) status code, as shown in the console

Click here I have a simple file structure where index.html, script.js, and login.js are all in the same root folder without any subfolders. The issue I'm facing is that although the connection to the database works fine, there seems to be a problem wi ...

Modify the REST request information according to the data retrieved from the preceding step's response

Currently, I am delving into the realm of test automation and attempting to utilize response values as inputs for the next request. However, a major roadblock I have encountered is that the response contains a dynamic list that can vary in length. Below i ...

In the virtual playground of Plaid's Sandbox, how can I replicate a fresh transaction and detect it using the Webhook feature?

Is there a way to trigger a simulated transaction within the webhook instead of just a DEFAULT_UPDATE event? I'm trying to find a way to simulate an actual transaction so that I can test my webhook integration. I've searched through the sandbox ...

I'm having trouble with Google Map InfoWindows not displaying when clicked within a loop

I'm facing an issue where the info window on Google Map API doesn't open on click within a loop, although all info windows show with an outside click event. var map; function initMap() { var mapProp = { center: new google.maps.LatLng( ...

Using PHP and JavaScript to determine device screen width and eliminate the $_GET parameters from the URL

I have implemented the following JavaScript code to detect screen width and utilize it as a constant throughout my template files using conditional statements to control the visibility of different sections on my site. Just to clarify, I am working within ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

Acquiring the specific checkbox value using JQuery

I am encountering an issue with my JQuery function that is supposed to print out the unique value assigned to each checkbox when clicked. Instead of displaying the correct values, it only prints out '1'. Each checkbox is assigned an item.id based ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

dijit.Tree: Managing Expand/Collapse Events

My mobile application requires Lazy Loading, so I need to handle the expand event. I am utilizing dijit.Tree from the Dojo library. However, the official documentation does not mention any onCollapse/onExpand events. I attempted to use the onClick event ...