Logan Voss Logan Voss - 2 months ago 9
JSON Question

How to access members of associative array from AJAX Response

I have a shorthand ajax call that triggers on a selection box change.

<script type'text/javascript'>
$('#selection_project').change(function(event) {
$.post('info.php', { selected: $('#selection_project option:selected').val()},
function(data) {
$('#CTN').html(data);
}
);
});
</script>


It works, but the response from the server is this:

if (isset($_POST['selected']))
$selected = $_POST['selected'];
$results['selected'] = $selected;
$response = json_encode($results);

echo $response;


$results is an associative array with many values from a SQL query.

My question is how do I access any particular element?
I've tried things like

data.selected


or,

data['selected']


I also understand that somewhere in the .post method there should be a statement defining the alternative dataType, such as

'json',


or a

datatype: 'json',


but after lots of searching, not a single example I could find could provide the actual syntax of using alternative dataTypes in the .post method.
I would have just used the .ajax method but after pulling my hair out I cannot figure out why that one isn't working, and .post was, so I just stuck with it.
If someone could give me a little push in the right direction I would appreciate it so much!!

EDIT: Here is my .ajax attempt, can't figure out why it's not working. Maybe i've been staring at it too long.

<script type'text/javascript'>

$('#selection_project').change(function(event) {
$.ajax({
type: 'POST',
url : 'pvnresult.php',
data: { selected: $('#selection_project option:selected').val()},
dataType: 'json',
success: function(data){
$('#CTN').html(data);
}
});
});

</script>

Answer

Try to log what exactly returned from info.php. Possible there are no data at all&

$('#selection_project').change(function(event) {
    $.post('info.php', {
        selected: $('#selection_project option:selected').val()},
        function(data) {
            console.log(data);
            $('#CTN').html(data);
       }
   );            
}); 

--- Update. Sorry, I can't leave comments

You shold parse your json with JSON.parse before use:

$('#selection_project').change(function(event) {
    $.post('info.php', {
        selected: $('#selection_project option:selected').val()},
        success: function(data){
            var result = JSON.parse(data);
            $('#CTN').html(data);
        }
    });
});