platanas20 platanas20 - 5 months ago 18
jQuery Question

Json data cannot be displayed in div section using Ajax and jQuery

I created a json of this format of a external php file:

[
{
"title": "Welcome!",
"description": "The world has changed dramatically..",
"image": "img/strawberry-wallpaper.jpg"
}
]


I am using this to display data to a specific div section but I have no results:

<script type="text/javascript">

$(document).ready(function(){
$.ajax({
url: 'json.php',
type: 'post',
data: { get_param: 'value' },
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(data){
var obj = jQuery.parseJSON(data);
if(obj.success){
$.each(obj, function (index, item) {
if ('success'!= index){
$('#output').append("<div class='col-md-6' ><img class='img-rounded' src="+item.image+"alt='MyImage' width='550px' height='240px'></div><div class='col-md-6'><h3>"+item.title+"</h3><p class='well'>"+item.description+"</p><div class='row top-buffer'><div class='col-md-5 col-md-offset-1'><img src='img/link_icon.png' class='img-rounded' width='20px' height='20px'/><a href='www.link.com'>liNK</a></div><div class='col-md-6'><button class='btn btn-primary pull-right' id='btn'>Read More</button></a> </div></div></div>")

});
}
};
});
});




Can anyone notice anything wrong to this code?The format of json is proper?

Answer

data is already a object converted by jQuery. You don't need to parse.

DEMO

$(function() {
    $.ajax({
        url: 'json.php',
        type: 'POST',
        data: {get_param: 'value'},
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function(data) {
            // check with console
            console.log(data);

            $.each(data, function(index, item) {
                $('#output').append("<div class='col-md-6' ><img class='img-rounded' src="+item.image+"alt='MyImage' width='550px' height='240px'></div><div class='col-md-6'><h3>"+item.title+"</h3><p class='well'>"+item.description+"</p><div class='row top-buffer'><div class='col-md-5 col-md-offset-1'><img src='img/link_icon.png' class='img-rounded' width='20px' height='20px'/><a href='www.link.com'>liNK</a></div><div class='col-md-6'><button class='btn btn-primary pull-right' id='btn'>Read More</button></a> </div></div></div>");
            });
        }
    });
});