0

I have two divs, each one should have a record name from a json result.

<div class="first"></div>
<div class="second"></div>

My json file is as follows :

 [{"Name":"name1","Instruction":"instr"},
 {"Name":"name2","Instruction":"instr again"}]

I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record. I'm using jQuery :

<script>
    $(document).ready(function() {
        $.post("data/result.php",
                function(data) {
                    //alert("Data: " + data);
                    $('div.first').append(data.Name); //data.Name returns undefined
                }
        );
    });
</script>

Any help would be appreciated.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
salamey
  • 3,633
  • 10
  • 38
  • 71

3 Answers3

0

as far as you are using post for you ajax call, the data returns as a json string, do this:

$(document).ready(function() {
    $.post("data/result.php",
            function(data) {
                data = JSON.parse(data);
                $('div.first').append(data[0].Name);
                $('div.second').append(data[1].Name);
            }
    );
});
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
0

As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:

<script>
    $(document).ready(function() {
        $.ajax({
        url: 'data/result.php',
        type: 'POST',
        dataType: 'json',
        success : function (data) {
            $('div.first').append(data[0].Name);
        }
        });
    });
</script>
Zabavsky
  • 13,340
  • 8
  • 54
  • 79
beije
  • 841
  • 5
  • 11
0

First of all, you can give a datatype with a request:

$.post('data/result.php',function(data) { },'JSON');

If you are not posting any information, why not just use $.get ? (it's the same syntax btw)

$.post('data/result.php',function(data) {
    var $first = $('div.first'),
        $second = $('div.second');
    $first.text(data[0].Name);
    $second.text(data[1].Name);
},'JSON');

Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

DoXicK
  • 4,784
  • 24
  • 22