1

I'm printing a <ul> of array $_SESSION['words'] in PHP.

    // PHP print new words as links
    echo '<ul id="wordlist">';
    foreach($_SESSION['words'] as $word => $description) {
        echo '<li id="wordlist"><a href="#">' . $word . '</a></li>';
    }

The array is simple - words are stored as keys and the descriptions for words will be values, e.g. array(5) { ["word1"]=> int(1) ["word2"]=> int(2) ["word3"]=> int(3) ["word4"]=> int(4) ["word5"]=> int(5) }

I plan to manipulate items in the array by selecting a $word and adding a $description and adding it to the array, so I'm thinking I'll use jQuery to do it.

My question is: if I create a JSON array from this PHP array, can I print it out in the same way and manipulate it? I encoded it with $myJSON = json_encode($_SESSION['words']); but I'm already stuck attempting to print out the keys/values from the JSON! Thanks...

4 Answers 4

2

You can use $.parseJSON:

var json = $.parseJSON('your json');
alert(json.word1);
alert(json.word2);

If your JSON data is available via a URL, you can use $.getJSON

Sign up to request clarification or add additional context in comments.

Comments

1

You description indicates to me that you are not using JSON in any way, other than to use PHP's JSON encoding function. It sounds like you are encoding your PHP associative array into a JSON string and then writing that string into your HTML output. If this is the case, then your JSON is really a JavaScript object.

So let's assume your resulting markup is this:

<script>
  // Using a global here, which is not good,
  // but this is an example.
  var myWordList = {"word1":1,"word2":2,"word3":3};
</script>
<ul id="wordlist">
  <li id="word1">1</li>
  <li id="word2">2</li>
  <li id="word3">3</li>
</ul>

Notice that my id attribute values are unique. You used the same id attribute value multiple times; that is invalid markup. Also, I kept the markup in each list element simple for this example (just text).

So, given this markup, we could write the following JavaScript:

<script>
// Update our wordlist object with some descriptions
myWordList.word1 = {
  "value": myWordList.word1,
  "description": "This is word 1."
};

myWordList.word2 = {
  "value": myWordList.word2,
  "description": "This is word 2."
};

myWordList.word3 = {
  "value": myWordList.word3,
  "description": "This is word 3."
};

// Now lets update the unordered list with jQuery
for (var i = 1; i < 4; i += 1) {
  $('#word' + i).html(myWordList['word' + i].description);
}
</script>

In this JavaScript, I first update the myWordList values by assigning a new object to each value. These new objects have two properties: a value property that is assigned the old myWordList.word# value, and a new description property that describes the word. Next, I update the unordered list by replacing the word values with the word descriptions.

Edit:

If you want to loop over the properties in the object, you can do this:

for (var key in myWordList) {
  if (myWordList.hasOwnProperty(key)) {
    console.dir(myWordList[key]);
  }
}

2 Comments

Thanks for this, I can see how I can build the jquery functions to manipulate the js object. However, I'm still bothered by just trying to print out the elements of the object in the first place!
@matski I have added an addendum that addresses your concern.
1
  1. if not used to $.each method, may also try old array loop:

    $.ajax({ 
      url: '',
      dataType: 'json', 
      success: function(arrayData) { 
        var i,max=arrayData.length; 
        for(i=0;i<max;i++){ 
           var rowItem = arrayData[i];
           try{
           console.log(rowItem.attr1);
           }catch(ex){
           alert(ex);///in case data is not complete
           }
        }); 
      } 
    });
    
  2. if you already have the JSON string , say strJson = '[{attr1:"hello"},{attr1:"world"}]';

    var tmp = 'var data = '+strJson; 
    ///so you got : var data = [{attr1:"hello"},{attr1:"world"}]
    eval(tmp);/// execute the above line
    alert(data.length + "first item:"+data[0].attr1);
    

3 Comments

2 is a very old fashion way, based on JSON is JavaScript (object notation)
I have the array ready in PHP. So if I want to use option (2) you mean I'd need to do var strJson = <? json_encode($_SESSION['words']); ?>; ?
var strJson = '<?= json_encode($_SESSION['words']); ?>'; // or var strJson = '<?php echo json_encode($_SESSION['words']); ?>'; // as json_encode will not output the string to html
0

You need to get that JSON via AJAX and the

$.ajax({
  url: '',
  dataType: 'json',
  success: function(response) {
    $.each(response, function(key, val) {
       console.log(key); // word1, word2, word3...
       console.log(val); // 1, 2, 3...
       ....
    });
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.