Reputation: 76240
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);
?>
Upvotes: 1
Views: 719
Reputation: 360572
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
Upvotes: 3
Reputation: 62573
It should be
if (index == 'name') { $('.name').html(value); }
if (index == 'password') { $('.password').html(value); }
Upvotes: 0