1

I have some problem. I have created some app that consuming JSON array.

The syntax is using Jquery 1.9

The logic is : getting values from textbox (valobj variable below) then write to toprightsec div area.

$("#btnsearch").click(function() {
        valobj = $('#search_box').val();
        $.getJSON("search.php", { q : valobj }, function(data,result){
            //show result from database
            $('toprightsec').append("Title" + data.title)
                            .append("Intro" + data.intro_text);
            //end show result
        }, JSON);
    });

JSON array is from PHP result. some example

{"content":[{"title":"Test Post 100","intro_text":"Intro Test"}]}

But, it's not working. any helps?

thanks in advance.

UPDATE

$("#btnsearch").click(function() {
    valobj = $('#search_box').val();
    $.getJSON("search.php", { q : valobj }, function(data,result){
        //show result from database
        $('.toprightsec').append("Title" + data.content[0].title)
                        .append("Intro" + data.content[0].intro_text);
        console.log(data)
        //end show result
    }, JSON);

UPDATE 2

$(document).ready(function () {

    $("#btnsearch").click(function() {
    valobj = $('#search_box').val();
    $.getJSON("search.php", { q : valobj }, function(data,result){
        //show result from database
        $.each(data.content, function() {
            $('.toprightsec').append("Title" + data.content[0].title)
                        .append("Intro" + data.content[0].intro_text);
        });

        //end show result
    }, JSON);
});
randytan
  • 1,029
  • 5
  • 23
  • 52

2 Answers2

2

Use the following code:

 $('.toprightsec').append("Title" + data.content[0].title)
                            .append("Intro" + data.content[0].intro_text);

instead of:

 $('toprightsec').append("Title" + data.title)
                            .append("Intro" + data.intro_text);

If toprightsec is id then use the # and if class then use the .. here you have not specify that.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

You are using json array,so you have to access single array element and not whole array:

json_array.title //WRONG 
json_array[0].title //OK

Try something like:

$("#btnsearch").click(function() {
        valobj = $('#search_box').val();
        $.getJSON("search.php", { q : valobj }, function(data,result){
            //show result from database
            if (data.length){
                var _props = data.pop().content;
                $('toprightsec').append("Title" + _props.title)
                                .append("Intro" + _props.intro_text);
            }
            //end show result
        }, JSON);
    });
elrado
  • 4,960
  • 1
  • 17
  • 15