Having trouble parsing JSON data using Ajax?

API Code :

$.ajax({
        type: "POST",
        url: "API URL",
        data: JSON.stringify(User),
        dataType : "json",
        success: function(apiResponse) {
            var session = apiResponse.sessionId;
            console.log ("Session ID: "+ session);

            $.ajax({
                type: "GET",
                url: "ANOTHER URL",
                dataType : "jsonp",
                contentType: "jsonp",
                success: function(apiResponse) {
                    console.log (apiResponse);
                    jQuery.each(apiResponse,function(){
                         console.log (apiResponse);
                                            });
                     },
                error: function(apiResponse) {
                    alert("Error: " +apiResponse);
                }
            });
        },
        error: function(apiResponse) {
            alert("Error: " +apiResponse);
        }

===========

PHP code that returns JSON data

<?php

$jsonp = false;
if ( isset( $_GET[ 'callback' ] ) ) {
    $_GET[ 'callback' ] = strip_tags( $_GET[ 'callback' ] );
    $jsonp              = true;
    $pre  = $_GET[ 'callback' ] . '(';
    $post = ');';
  } //isset( $_GET[ 'callback' ] )

 /* Encode JSON, and if jsonp is true, then ouput with the callback
 ** function; if not - just output JSON. */
 $json = json_encode( '{"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}' );
print( ( $jsonp ) ? $pre . $json . $post : $json );

ANOTHER URL returns following data

  {"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}

================ Now experiencing the following error along with console.log details

   Session ID: 67a47816-5a03-44f9-ab24-01e1e8d4aad1

  {"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}

   TypeError: invalid 'in' operand e
   [Break On This Error]    

   ...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r...

=======================

What I want: 1. Parse the Json response. "Top Cat1" goes to list heading listings under it.

What I am doing wrong.

Answer №1

Is it necessary to use the function json_encode on a string that is already encoded in JSON format?

$json = json_encode( '{"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}' );

It is advisable to do it this way:

$json = '"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}';

The purpose of using json_encode is to handle cases like this:

$arrayTemp = array("top cat1"=>array(array("id"=>"cat1","name"=>"product1"),array("id"=>"cat2","name"=>"product 2")),"top cat2"=>array(array("id"=>"cat3","name"=>"product 3"),array("id"=>"cat4","name"=>"product 4")));

$json = json_encode($arrayTemp);

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

Updating the language of the months displayed in the popup calendar

I am attempting to change the language of the clickDate function from English (Jan, Dec, etc.) to another language. However, I am struggling to find a way to do so because I only have access to the scripts provided below. The idate is in the format 2015073 ...

Using React and Ant Design: Sharing state between multiple <Select> components within a <Form> element

Just getting started with ReactJS and AntDesign. Currently, I am working on connecting a series of <Select> components to share state. The goal is for the selection made in the first dropdown to dynamically update the options available in the follow ...

Lazyload feature in Ajax is not functioning as expected

For the past week, I've been struggling to implement infinite scroll in WordPress. Despite trying various plugins and coding languages such as Javascript, JQuery, and PHP, I haven't been successful due to my lack of confidence in these areas. ...

How to transform a sentence string into an array of individual words using Ionic 2

I need to convert a string of words separated by new lines into an array called "words." aa aaa aaaa aaaaa In Java, I would do it like this: String s = "This is a sample sentence."; String[] words = s.split("\\s+"); for (int i = 0; i < word ...

What is the best way to add a new li element to a ul list that shares the same class name

Is there a way to add a new li element to the ul on the right side? Each card comes with a ul and a form. After submitting the form, I want to append a new li to the corresponding ul. Each ul has a class of .topics. However, the new li is currently being ...

Ensuring JSON schema validation during the processing of a POST request and retrieving user-input POST data utilizing a Spring Boot REST API

Is it possible to validate a JSON input from a user with a specified schema through a POST request using a specified schema? We need to ensure that the JSON data is validated every time it is received via the POST request. Additionally, how do we extract t ...

The hover effect and image opacity adjustment seem to be malfunctioning in my HTML/CSS code

Currently, I am in the midst of a web project and my goal is to implement a hover effect on the first card containing an image. The desired outcome is for the card to move upwards upon hovering, allowing the image to become fully visible with an opacity se ...

Populating a multi-layered array using JSON data

My goal with this code is to populate a global array with JSON objects. // declaring global arrays var sectionL=[1,5,3,7,5,4,3,3,4,4,6,6,3,5,5,1]; var sectionsTitle=new Array(16); var sectionsContent=new Array(16); for(var i=0; i<sectionL.length;i++){ ...

The data type 'void' cannot be assigned to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'

Can you assist me in understanding what has occurred and provide guidance on the necessary steps to resolve it? I am currently working on a website where I am in need of hooks to update the state. The issue seems to be related to the onClick events within ...

What is the best way to conduct a Javascript test using Jasmine?

I'm encountering an issue with testing this JavaScript code: $("#ShootBtn").on('click', () => foo.testFunc()); var foo = { testFunc: function() { hub.server.shoot(true, username, gameCode); } } For my testing framework, ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

Determine if the browser is utilizing GPU acceleration for rendering graphic content

Currently working on a large-scale website that utilizes CSS3 transitions for animations (leveraging jaquery.transit to manipulate element transitions and their CSS styles). Encountered two challenges in the process: It appears that Firefox (latest updat ...

How come my test completes prior to the synchronous event handler of my (enzyme-simulated event)?

In my testing environment, I am encountering a scenario where my mocha based test finishes before the onChange handler in an enzyme test of my React component. Despite the fact that the handler is synchronous and uses babel+ES2017. Interestingly, if I add ...

Display JSON information in the present moment

I am looking to display only 2 results from a JSON file based on the current time. For example, at 11:00 am today, I want to show only the second and third items. JAVASCRIPT $(data.users).each(function() { var output = "<ul><li>" + this.first ...

Tips for comparing props in the ComponentDidUpdate method when dealing with a complex data structure that is connected to Redux

I have been experimenting with the new lifecycles of React v16. It works perfectly fine when comparing single keys. However, when dealing with large data structures like Arrays of objects, performing deep comparison can be quite expensive. My specific sce ...

Experiencing ERR_TOO_MANY_REDIRECTS while using Next.js with Vercel and a Custom Domain through Cloudflare

I'm having trouble getting my Next.js project set up on Vercel with a custom domain managed through Cloudflare. Despite configuring the DNS and SSL settings correctly, I keep seeing a net::ERR_TOO_MANY_REDIRECTS error when trying to access my site at ...

Background with borders full of parallax effects scrolling in sync

I'm completely new to the world of HTML and CSS, and I was hoping for some guidance. I've been trying to wrap my head around a tutorial on creating parallax scrolling websites, which you can find here: However, I noticed that the tutorial includ ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

Redirecting to the next page once the Bootstrap validator has successfully processed

I am currently utilizing CodeIgniter framework for my project. In the view file, I have a form where I implemented Bootstrap validator for field validation. The Bootstrap validator is successfully validating the form fields. However, the issue arises when ...

How to give focus to a div in IE 8 after pressing the tab key, no jQuery required

We are facing a challenge with our datagrid where we have implemented navigation using the tab key. In IE 7 & 8, pressing the tab key shifts the focus away from the grid to the next element on the page. While in other browsers, we were able to prevent thi ...