Tony33 Tony33 - 5 months ago 45
JSON Question

Dynamically add elements with ajax and json breaks the page layout

I have a page structured with jquery mobile. If i populate a list with a static code:

<script>
document.write('<ul data-role="listview">');


document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></a></li>');
document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></a></li>');



document.write('</ul>');

</script>


i get this result: image

Now, i try to do it dinamically, reading from a database with ajax and json.
This is the code:

<script>
document.write('<ul data-role="listview">');
$.ajax({
url: 'db_to_app_prod.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){

document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></a></li>');

});

},
error: function(){
output.text('There was an error loading the data.');
}
});


document.write('</ul>');
</script>


And this is the result: image
As you can see, the layout is totally broken now. What happens? Why? How do i fix this to obtain dinamically the first result?

EDIT:
This is another try i did:

$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});


//var output = document.getElementById("output");
var _ul = document.createElement('ul');

_ul.setAttribute("data-role", "listview");


$.ajax({
url: 'db_to_app_prod.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){

var _li = document.createElement('li');
_li.setAttribute("data-icon", "false");
_li.innerHTML = '<li data-icon="false">'+
'<a href="" id="'+item.id+'">'+
'<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'">'+
'<h2>'+item.marca+'</h2>'+
'<p class="wrap">'+item.descrizione+'</p>'+
'<span class="ui-li-count">'+item.prezzo+' €</span>'+
'</a></li>';

_ul.appendChild(_li);

});

},
error: function(){
output.text('There was an error loading the data.');
}
});
document.getElementById("output").appendChild(_ul);

});

Answer

Something like this:

    .....
    success: function(data, status){
        var _ul = $('<ul />').attr('data-role','listview');
        $.each(data, function(i,item){ 

            $('<li data-icon="false" />')
               .append($('<a href="" id="'+item.id+'" />')
                 .append('<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'" />')
                 .append('<h2>'+item.marca+'</h2>')
                 .append('<p class="wrap">'+item.descrizione+'</p>')
                 .append('<span class="ui-li-count">'+item.prezzo+' €</span>')
                )//$('<a />')
            //)//$('<li />') no need sorry
            .appendTo(_ul);   
        });
        $('#output').empty().append(_ul);
    },
....

Also dataType:'json' not jsonp. see http://api.jquery.com/jquery.ajax/ specification

Update

Full working code. Works with your sample json.

        $.ajax('tony.js?id=' + Math.random(), //fake json which match your structure
            {
                dataType: "json",
                jsonp: "jsoncallback",
                method: 'get',
                contentType: 'application/json',
                success: function (data, status) {
                    var _ul = $('<ul />').attr('data-role', 'listview');
                    $.each(data, function (i, item) {
                        $('<li data-icon="false" />')
                           .append($('<a href="" id="' + item.id + '" />')
                             .append('<img src="http://gestisciapp.it/gruppodipalo/images/' + item.img + '" />')
                             .append('<h2>' + item.marca + '</h2>')
                             .append('<p class="wrap">' + item.descrizione + '</p>')
                             .append('<span class="ui-li-count">' + item.prezzo + ' €</span>')
                            )//$('<a />')
                        .appendTo(_ul);
                    });
                    $('#output').empty().append(_ul);
                },
                error: function (xhr, d, s) {
                    $('#output').empty().html(s);
                }
            });

Full Working Example

Tested in Google mobile emulator tool.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
    <script type="text/javascript">
        function getData() {
            $.ajax('tony.js?id=' + Math.random(), //fake json which match your structure
                {
                    dataType: "json",
                    jsonp: "jsoncallback",
                    method: 'get',
                    contentType: 'application/json',
                    success: function (data, status) {
                        var _ul = $('<ul />').attr('data-role', 'listview');
                        $.each(data, function (i, item) {
                            $('<li data-icon="false" />')
                               .append($('<a href="" id="' + item.id + '" />')
                                 .append('<img src="http://gestisciapp.it/gruppodipalo/images/' + item.img + '" />')
                                 .append('<h2>' + item.marca + '</h2>')
                                 .append('<p class="wrap">' + item.descrizione + '</p>')
                                 .append('<span class="ui-li-count">' + item.prezzo + ' €</span>')
                                )//$('<a />')
                            .appendTo(_ul);
                        });
                        $('#output').empty().append(_ul).enhanceWithin();//.listview();
                    },
                    error: function (xhr, d, s) {
                        $('#output').empty().html(s);
                    }
                });
        }
    </script>
</head>
<body>
    <button onclick="getData()">Get Data</button>
    <div id="output"></div>
</body>
</html>
Comments