1

I'm probably misunderstanding JSON, but why this code doesn't work?

HTML

<html>
    <head>
        <title>Test</title>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
    </head>
    <body>
        <div class="response">
            Name: <span class="name"></span><br>
            Password: <span class="password"></span><br>
    </body>
</html>

MAIN.JS

$(document).ready(function(){

    $.ajax({
        type: "POST",
        url: 'action.php',
        dataType: 'json',
        success: function(msg){
            $.each(msg, function(index, value){
                if (index == 'name') { $('.name').html(value.name); }
                if (index == 'password') { $('.password').html(value.password); }
            });
        },

        error: function(){
            $('.response').html("An error occurred");
        }
    });

});

ACTION.PHP

<?php

$array = array(
    0 => array(
        'name' => "Charlie",
        'password' => "none"
    ),
    1 => array(
        'name' => "Tree",
        'password' => "tree"
    )
);

echo json_encode($array);

?>
Shoe
  • 74,840
  • 36
  • 166
  • 272

2 Answers2

3

In your javascript, index will be '0' and '1', never 'name' and 'value':

    success: function(msg){
        $.each(msg, function(index, value){
            $('.name').html(value.name);
            $('.password').html(value.password);
        });
    },

Of course, as this stands now, you'll be setting your fields twice, and only the last one will "stick"

If you wanted use just the 'Charlie' result, then

    success: function(msg){
        $('.name').html(msg[0].name);
        $('.password').html(msg[0].password);
    },

and for 'Tree', just change the array subscripts to 1

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • @adarsh. No, the loop is over the JSON data returned from PHP, which is a 2 element array with indexes 0 and 1, each of which contains an associative array with the name/password pairs. – Marc B Feb 21 '11 at 15:44
  • @Marc B, What if i'd like that every results from the JSON object is shown in a different
    div?
    – Shoe Feb 21 '11 at 15:48
  • Then you'd either have to have unique IDs on each set of name/password divs (created in advance), or dynamically create the pairs on each loop iteration and insert into the DOM. Not hard, just a few more lines of code. – Marc B Feb 21 '11 at 16:00
  • @Marc B, i didn't got this. Could you please provide an example? – Shoe Feb 21 '11 at 16:05
  • I tried something, but it seems not to be working, could you please give a look? http://stackoverflow.com/questions/5068449/strange-loop-behavior-with-json-and-ajax – Shoe Feb 21 '11 at 16:31
0

It should be

if (index == 'name') { $('.name').html(value); }
if (index == 'password') { $('.password').html(value); }
adarshr
  • 61,315
  • 23
  • 138
  • 167