Json object not recognized

I am in the process of developing a basic application where the user can interact with a button to retrieve a JSON object from the database. The object's structure is displayed below. However, the system is failing to recognize the object, resulting in execution errors. Any insights on why this might be occurring?

Here is the array response from PHP being passed to JavaScript

array(2) (
  [success] => (bool) true
  [cnt] => array(2) (
    [2014-11-28] => array(2) (
      [visits] => (string) 1115
      [searches] => null
    )
    [2014-11-29] => array(2) (
      [visits] => (string) 493
      [searches] => 0
    )

    )
)

JSON object structure

{
   "success":true,
   "cnt":{
      "2014-11-28":{
         "visits":"1115",
         "searches":null
      },
      "2014-11-29":{
         "visits":"493",
         "searches":0
      }
   }
}

Snippet of the function responsible for parsing the object

 $.post(JOBK.ajaxurl, data, function (resp) {
            if (resp.success) {

                // Append rows    
                $.each(resp.cnt, function (dateCol) {
                    $.each(dateCol, function (visitsCol, searchesCol) {
                        // Insert a row in the table at row index 0
                        var newRow = tableRef.insertRow(tableRef.rows.length);

                    });
                });
            }

        }, 'json');
    });

Answer №1

First and foremost, ensure that your JSON string is valid.

{"success": true, "data": {"2020-07-15": {"visits": "835", "searches": null}, "2020-07-16": {"visits": "420", "searches": 0}}}

Additionally, consider eliminating the need for a nested loop and simplify to just one loop:

// Process data        
$.each(response.data, function (dateKey, data) {
   var visits = data.visits;
   var searches = data.searches;
   //... perform operations here
});

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

Executing a function by clicking on a DIV with the value of a textbox, instead of clicking directly on the textbox

Here is a function I have: $("#border-radius").click(function(){ var value = $("#border-radius").attr("value"); $("div.editable").click(function (e) { e.stopPropagation(); showUser(value, '2', this.id) $(this).css( ...

Ways to extract dropdown selection into a .php script

I am trying to capture the selected dropdown value in my .php file, which is used for sending emails. When a user selects one of the 6 options from the dropdown menu, I want that selected option to be included as the email subject. Below is the HTML code ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...

The form data is getting duplicated during the XMLHttpRequest process, resulting in one submission with an empty object and another with the accurate data

Currently diving into the world of web development and AJAX, I'm utilizing the XMLHttpRequest object on my browser along with Node using Express as my server. I have a basic HTML form that should post data to the Node server. Confirming that the data ...

boosting the maximum number of requests allowed

What can be done to increase the request limit if the user continues to hit rate limits? This is my current rate limiter setup: const Limiter = rateLimit({ windowMs: 10000, max: 5, standardHeaders: true, legacyHeaders: false, keyGenerator: funct ...

Tips for correctly setting the encoding for json.load

I've run into an issue when trying to load JSON using the following code: data = json.load(f) The JSON file I'm working with has windows1251 encoding, which is causing an error upon opening it: File "./labelme2voc.py", line 252, in main da ...

Is it feasible to implement automatic window closure on the alternate website?

Imagine I have a website, let's say http://myownsite.com, and my desire is to execute a script that will open a new window on Safari or any other browser for a site which I do not own: http://theothersite.com If I lack control over that specific site ...

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...

Utilizing AJAX for file and data uploading in combination with Spring MVC and JSP

Struggling to create code for file and data uploading... Finding it difficult...!!!!!!!! Clicking "btn-upload" button does not trigger any response... No error message in eclipse... Seeking help, please assist...! This is JSP. <script> $("#btn- ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

Ways to store a component in cache once its route is triggered

There are 3 components in my project: 1 parent and 2 child components with router outlet. The child component becomes active whenever its route is called, sharing data using a service. Both of these child components have complex views. When switching bet ...

Converting webpage JSON data to Python script encountered an error: urllib.error.HTTPError: HTTP Error 403 - Forbidden access

I successfully developed a program that functions with a local JSON data file! Code Block: def datas(self): with open ("C:\\Users\\Messi\\Desktop\\Python\\\\tek.json ...

The information retrieved from an API fails to populate the table on the NextJS platform

I am facing an issue while trying to populate a table using an API call in NextJS. I have used the getStaticProps function to retrieve the data and pass it to the component. However, when I attempted to use the map() function to iterate over the data objec ...

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

Trouble with parsing JSON data in JQuery getJson callback

Recently, I've encountered a strange issue with using jQuery for JSON. Even though the server is responding correctly to the request, I'm having trouble extracting the data from the JSON response. The server is ASP.MVC and is serializing using J ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Changing the rotation of an object in THREE.js to match Canvas rotation

Hello amazing minds of stackoverflow. I am in the process of converting three js mesh positions to html5 canvas positions. While I have successfully converted vector3 position to canvas position, I am facing difficulties with converting mesh rotation to ca ...

Embed full content in iframe using bootstrap 4

Embedding an iframe of an appointment scheduling frontend on my page has been a challenge. While the width is correct, the height of the frame is too small. Despite attempting various CSS modifications, I have not been able to achieve the desired result. I ...

Exploring nested arrays of objects and applying value constraints

Is there a way to iterate through an array and display only 5 items at once, with the option to call a function on click that will add another 20 items? I have an object structured like this: let someObject = [ { data: [ { id: 123, ...