Incorporating elements dynamically using ajax and json can disrupt the overall design of the page

I have structured a page using jQuery Mobile. If I populate a list with 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>

After populating the list with static code, this is the result.

Now, I am attempting to do it dynamically by reading from a database using AJAX and JSON. This is the new 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>

After switching to dynamic population using AJAX and JSON, the layout is now broken. What could be causing this issue? How can I fix it to achieve the same dynamic result as the initial static approach?

EDIT: I made another attempt with the following code:

$(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 №1

Here is an example of how you can achieve 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://example.com/images/'+item.img+'" />')
                 .append('<h2>'+item.brand+'</h2>')
                 .append('<p class="wrap">'+item.description+'</p>')
                 .append('<span class="ui-li-count">'+item.price+' $</span>')
                )
            .appendTo(_ul);   
        });
        $('#output').empty().append(_ul);
    },
....

Make sure to use dataType:'json' instead of jsonp. You can find more details in the jQuery AJAX documentation.

Update

Below is a fully functional code snippet that works with the provided sample JSON data.

        
$.ajax('sample.json?id=' + Math.random(), 
{
    dataType: "json",
    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://example.com/images/' + item.img + '" />')
                 .append('<h2>' + item.brand + '</h2>')
                 .append('<p class="wrap">' + item.description + '</p>')
                 .append('<span class="ui-li-count">' + item.price + ' $</span>')
                )
            .appendTo(_ul);
        });
        $('#output').empty().append(_ul);
    },
    error: function (xhr, d, s) {
        $('#output').empty().html(s);
    }
});

Full Working Example

This code has been tested using the Google mobile emulator tool.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://cdn.example.com/jquery.mobile.min.css">
    <script src="https://cdn.example.com/jquery-2.1.4.min.js" type="text/javascript"></script>
    <script src="https://cdn.example.com/jquery.mobile.min.js"></script>
    <script type="text/javascript">
        function getData() {
            $.ajax('sample.json?id=' + Math.random(),
                {
                    dataType: "json",
                    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://example.com/images/' + item.img + '" />')
                                 .append('<h2>' + item.brand + '</h2>')
                                 .append('<p class="wrap">' + item.description + '</p>')
                                 .append('<span class="ui-li-count">' + item.price + ' $</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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...

The issue of v-bind:checked not functioning properly across all component instances

Presenting a unique radio list component: <template> <div class="list"> <div class="radio"> <input type="radio" name="custom-radio-list" :id="'custom-radio-full-' + cid" value="" @change="updateCustomRadio" ...

Showcasing the progress of file upload (a variable) using SweetAlert

Is there a way to create a variable that tracks the uploading percentage of a file using SweetAlert? My development environment is PyCharm with Django as the GUI framework. I have searched through various resources related to Ajax, PHP, and SweetAlert but ...

Retrieving data attributes from model within a Backbone view using Underscore template

I have a Backbone.js view that I'm working with: var StreamV = Backbone.View.extend({ tagName: 'div', className: 'stream', events: { }, initialize: function () { this.listenTo(this.model, 'change' ...

The initial state in NextJS fails to update when routing to the same page with different parameters

This particular project utilizes NextJS The structure of my page's URL is as follows: localhost:3000/first/second When I invoke getInitialProps on this page, the data retrieved from it is passed to the component and used to set the initial state li ...

Is there a way to stop the dropdown menu from disappearing when clicking on a popover that was activated from the dropdown?

Are you familiar with creating a popover that is triggered by a dropdown menu using the Twitter Bootstrap javascript components? Could you provide guidance on how to prevent the dropdown menu from closing when a user clicks on the popover? For reference, ...

Error: Unable to access length property of null object. Can you explain this to me?

One of my questions that I'm trying to solve is about the error message "Cannot read properties of null (reading 'transition'). What does it mean?". I tried using the solution suggested in this question on integration of 'mychart.update ...

The laggy response occurs when clicking following an ajax request

My sidebar is experiencing lag after an ajax call. Here is the code snippet: $(document).ready(function () { $.post("<?php echo $baseurl;?>/api-cart-top.php",{ unique: "<?php echo $unique;?>" }, function(data) { ...

Modify an aspect of the object and return it

After receiving a JSON object from an API, I am looking for a way to update only one user within the object. For example, let's say I want to update userId 4 without having to modify the entire JSON structure. Instead of updating the user individuall ...

Constrained and Proportional Resizing with KineticJS

Dragging any of the 4 corner handles of the image should result in proportional scaling, either up or down. Issue: I am facing a problem with my current approach as illustrated in the provided link to jsfiddle. When the topLeft handles are moved verticall ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

Switching the custom cursor depending on the operating system

I am faced with a challenge of customizing the cursor for my application. The issue is that cursors appear differently in OSX compared to Windows; black in OSX and white in Windows. I am considering creating two different cursors, one in white and one in ...

React Native application crashes when the user presses the input field

How can I fix the issue where pressing input text for 3 seconds displays the message "Application name is stopped"?........................................................................................... https://i.sstatic.net/a0Ym8.jpg Here is my compo ...

What could be the reason for the error message (JSON ERROR: no value for)?

I have been working on a Kotlin code to fetch data for a dictionary app using JSON Request Object. The call seems to be successful as I can see the website receiving the data, but I'm encountering an issue where the results object is not being populat ...

Troubleshooting Problem with Owl Carousel Navigation Buttons

I am encountering a minor issue with OWL Carousel - the owl-buttons div is overlapping my images. This makes it difficult to click on the small images within the owl-buttons div zone as that part of the screen is unresponsive. <script type="text/javasc ...

Add the child's input query first and then concentrate on it

I have successfully appended a div with a child input, but I am facing an issue where the newly appended input is not getting focused when added. $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper ...

To activate the javascript function, the hyperlink requires a double click

There is a hyperlink in my code and I want to trigger a function upon clicking that hyperlink. The function does work, but the issue is that it requires two clicks to execute. I have searched online for a solution but haven't found anything that reso ...

Preserving input values while navigating to a different page using React Router

I've created a form where the address fields can be auto-filled by selecting an Address that redirects you back to the form and populates the input values. To achieve this, I'm using the useNavigate() function to navigate to the Address Look-up ...

Is it possible to utilize global variables within CSS properties?

I have a scenario where I need to dynamically change values in an animation. The line of code that needs modification is: clip-path: polygon(var(clip1) 0, 100% 1%, 100% 100%, 50% 100%); let root = document.documentElement; root.style.setProperty('c ...

What are the signs of a syntax error in a jQuery event like the one shown below?

One of my forms has an ID attribute of id ='login-form' $('#login-form').submit(function(evt) { $('#login-button').addClass('disabled').val('Please wait...'); evt.preventDefault(); var postData = ...