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);
?>
In your javascript,
indexwill be ‘0’ and ‘1’, never ‘name’ and ‘value’: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
and for ‘Tree’, just change the array subscripts to
1