0

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

5 Answers5

1

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);
});
Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
  • Thanks a lot for this - your explanation makes sense but this still returns the same error as in the above answer. In Chrome: "Uncaught SyntaxError: Unexpected token A" - in FF: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" – WhistleBlower Jul 21 '15 at 05:20
1

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);
          });
      }
  });
Sathish
  • 2,440
  • 1
  • 11
  • 27
  • Thanks a lot for this as welll ! - Both approaches return a new error: "Uncaught TypeError: Cannot use 'in' operator to search for 'length'" – WhistleBlower Jul 21 '15 at 05:30
  • use `dataType:'json',` let me know – Sathish Jul 21 '15 at 05:40
  • Thanks. When I use this then the console logs nothing - it seems then my PHP doesn't return anything. – WhistleBlower Jul 21 '15 at 06:22
  • Thanks and sorry for the delay ! I just added my PHP to the post. – WhistleBlower Jul 21 '15 at 06:47
  • I seen your php its fine, now you try with my updated scripts above!! – Sathish Jul 21 '15 at 06:55
  • Thanks so much for all your effort ! I am still getting the same errors or nothing in the console. It seems to me that the problem is dataType: "JSON" as whenever I add this I am not getting anything back from my PHP and otherwise I cannot do anything with the data received as suggested. – WhistleBlower Jul 21 '15 at 08:20
  • Thanks again - I finally figured out what was causing this and posted it as an answer since this was something different. – WhistleBlower Jul 21 '15 at 08:51
1

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);
});
koredalin
  • 446
  • 3
  • 11
  • Thanks a lot for this as well ! I did some more research and this might actually be it since all other approaches failed so far. Can you explain where and how I have to apply this ? I have never used it before. – WhistleBlower Jul 21 '15 at 08:23
  • Take a look at [my comment](http://stackoverflow.com/questions/31530727/json-encode-not-working-with-get/31530860#31530860) there. – koredalin Jul 21 '15 at 08:57
  • Do you realy need to make your JS variable arr an jQuery object? You can try this. $.each(arr, function(key,value){ console.log(value.itemVal); }); – koredalin Jul 21 '15 at 09:04
0

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);

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

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.

Community
  • 1
  • 1