WhistleBlower
WhistleBlower

Reputation: 5

jQuery: How to iterate through JSON encoded string (array)

I am a jQuery beginner and hope someone can help me with this and also provide me some explanations.

I have an Ajax call that returns a JSON encoded string with two values for each item, an itemID and an itemVal - an example looks as follows (using console.log):

console.log(data) result:

string(225) "[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"},...]"

The number of items here varies but if an itemID is listed than there is always a corresponding itemVal.
itemID is a unique integer, itemVal is plain text.

Everything works so far but here comes my problem:
For each itemID here I have to do something with the corresponding itemVal, e.g. say just log it to the console or alert it for testing.

I know there are various approaches for this like jQuery.each, $.each, for, foreach etc. but since I just started recently I am not sure how I can iterate through this resp. how I can select the single itemIDs from it.

I tried different approaches, incl. $.parseJSON(data) which failed and it seems the problem is that my input before being decoded is a two-dimensional array instead of a one-dimensional one (I hope I am using the right terms here) which caused them to either return an error or to alert every single character of my string.

Update - failing example as per the answer below

$.ajax({        
    type: "post",   
    url: "ajax.php",
    cache: "false",
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a list of integers
    },
    success: function(data){
        console.log(data);
        var arr = JSON.parse(data);
        $.each($(arr),function(key,value){
           console.log(value.itemVal);
        });
    }
});

Update 2 - My PHP:

case "fetchCountries":
    $intval_itemIDs = array_map("intval", $_POST["itemIDs"]);
    $itemIDs = implode(",", $intval_itemIDs);

    $stmt = $conn->prepare("SELECT itemID, en FROM Countries WHERE itemID IN(" . $itemIDs . ") ORDER BY itemID");
    $stmt->execute();
    $result = $stmt->get_result();
    while($arrCountries = $result->fetch_assoc()){
        $countries[] = array("itemID" => $arrCountries["itemID"], "itemVal" => $arrCountries["en"]);
    }
    var_dump(json_encode($countries));
    break;

Expected outcome (for testing):

console.log("China");
console.log("France");
console.log("Germany");
// ...

Can someone help me with this ?

Many thanks, Tim

Upvotes: 0

Views: 4293

Answers (5)

WhistleBlower
WhistleBlower

Reputation: 5

Thanks to everyone for the help with this.

Since all other approaches made sense to me but still failed I did some more research on this and finally found what was causing this.

The issue was indeed on the PHP side and the accepted answer on the following post did the trick - since I added this to my PHP everything else on the JS side is working fine and I don't even need the dataType: "JSON" there:

dataType: "json" won't work

As per this post the solution for my case is the following - kudos to Jovan Perovic:

<?php
//at the very beginning start output buffereing
ob_start();

// do your logic here

// right before outputting the JSON, clear the buffer.
ob_end_clean();

// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>

Thanks again.

Upvotes: 0

Sathish
Sathish

Reputation: 2460

You're not parsing a string, you're parsing an already-parsed object

just use it directly

var data=[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}];

    $.each(data,function(key,value){
        console.log(value.itemVal);
    });

or/

 var arr = JSON.parse(JSON.stringify(data));

    $.each(arr, function (key, value) {
        console.log(value.itemVal);
    });

Update 1:

I think so your php file like

    <?php 
      $array = array( array( 'itemID' => 1, 'itemVal' => 'India'), array( 'itemID' => 2, 'itemVal' => 'usa'), array( 'itemID' => 3, 'itemVal' => 'china'), array( 'itemID' => 4, 'itemVal' => 'uk'));
        echo json_encode($array);
//[{"itemID":1,"itemVal":"India"},{"itemID":2,"itemVal":"usa"},{"itemID":3,"itemVal":"china"},{"itemID":4,"itemVal":"uk"}]
     ?>

your script should be

  $.getJSON( "your.php", function( data ) {
              console.log(data);
                $.each(data, function (key, value) {
                    console.log(value.itemVal);
                });
            });

OR

  $.ajax({        
          type: "post",   
          url: "your.php",
          cache: "false",
          dataType: 'json',
          data: {
              node: 'fetchCountries',
              itemIDs: youval // a list of integers
          },
          success: function(data){
              console.log(data);
                var arr = JSON.parse(JSON.stringify(data));
              $.each($(arr),function(key,value){
                 console.log(value.itemVal);
              });
          }
      });

OR

    $.ajax({        
      type: "post",   
      url: "your.php",
      cache: "false",
      dataType: 'json',
      data: {
          node: 'fetchCountries',
          itemIDs: youval // a list of integers
      },
      success: function(data){
          console.log(data);
          $.each($(data),function(key,value){
             console.log(value.itemVal);
          });
      }
  });

Upvotes: 3

koredalin
koredalin

Reputation: 445

WhistleBlower, I have tested your code on my browser. It worked. Why don't you use header("Content-type :application/json"); too. So, you will not have to parse your JSON string.

var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
   console.log(value.itemVal);
});

Upvotes: 1

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

As simple as this!

$.each($(data),function(key,value){
   console.log(value.itemVal); //place alert if you want instead of console.log
});

iterate through the obtained result and get itemVal value of each item

DEMO HERE


UPDATE

Add dataType option to your ajax and return type from php should be json and I hope you are doing that!

$.ajax({        
    type: "POST",   
    url: "ajax.php",
    cache: "false",
    dataType:'json', //Add this
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a list of integers
    },
    success: function(data){
        console.log(data);
        var arr = JSON.parse(data);
        $.each($(arr),function(key,value){
           console.log(value.itemVal);
        });
    }
});

and return from your php should be echo json_encode(result);

Upvotes: 0

Alex McMillan
Alex McMillan

Reputation: 17952

You have a JSON string representing an Array, which you are parsing into an actual Array. Then you are looping through the array, pushing each element into a new Array (arr).

Perhaps there is some confusion. Hopefully this will shed some light.

// Considering the following JSON string:
var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';

// You can create an Array from this like so:
var theArray = JSON.parse(data);

// Now you have an array with each item being an `object`
// with an "itemId" and an "itemVal".  You can loop through
// this array and look at each object like so:
theArray.forEach(function (obj) {
    console.log(obj.itemID + ': ' + obj.itemVal);
});

Upvotes: 1

Related Questions