Generating a JQuery mobile page on the fly using JSON data

Currently, I am working on developing a Jquery mobile app within cordova. My goal is to dynamically construct the entire page based on Remote Restful JSON results. Since the content of this page is not fixed and will change when the JSON data on the server changes, it needs to reflect those changes in real-time on the mobile app.

I have successfully retrieved the JSON data and created the necessary JQuery markup elements within the onDeviceready function. I can even view the HTML markup through an alert message.

However, when I attempt to add this constructed markup to the body tag, nothing appears on the screen. The Emulator simply displays a blank page.

Could someone please point out what I might be doing wrong? Any suggestions for the correct approach to achieve the desired outcome would be greatly appreciated.

app.js

var firstPageContent = "";

var loadMainPage = function(ussdArray) {
    var page = "<div data-role='page' id='home'> <div data-role='header' style='text-align:center;'>Company</div> <div data-role='content'>";
    page += "<ul data-role='listview' data-theme='b' data-inset='true'>";
    for (var x = 0; x < ussdArray.length; x++) {

    page += "<li data-inline='true'><a href='tel:"+ussdArray[x].UC+"'>"+ ussdArray[x].desc + " </a></li>";
    }
    page += "</ul></div> <div data-role='footer'></div></div>";//<co>
    firstPageContent += page;
};

$( document ).on( "deviceready", function(){    
        $.ajax({
        url: "http://1-dot-pmuthuvel1.appspot.com/eussd/serv",
        dataType: "text",
        success: function(dataTest) {
            var json = $.parseJSON(dataTest);
            var ussdValuesArr = json.ussd;
            loadMainPage(ussdValuesArr);
            alert(firstPageContent);
            $('body').html( firstPageContent );
        }
    });

});

index.html

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1, minimum-scale=1, maximum-scale=1">
<meta charset="utf-8">
<title>TestApp</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile.structure-1.4.4.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<script src="js/app.js"></script>
</body>
</html>

Answer №1

To initiate the create event, you need to trigger it in case of a cross-origin ajax request. Make sure to enable CORS and address any related issues in the script. The final code should resemble the following:

<script type="text/javascript">
    var firstPageContent = "";

    var loadMainPage = function (ussdArray) {
        var page = "<div data-role='page' id='home'> <div data-role='header' style='text-align:center;'>Company</div> <div data-role='content'>";
        page += "<ul data-role='listview' data-theme='b' data-inset='true'>";
        for (var x = 0; x < ussdArray.length; x++) {

            page += "<li data-inline='true'><a href='tel:" + ussdArray[x].UC + "'>" + ussdArray[x].desc + " </a></li>";
        }
        page += "</ul></div> <div data-role='footer'></div></div>"; //<co>
        firstPageContent += page;
    };

    $(function () {
        $.support.cors = true;
        $.ajax({
            url: "http://1-dot-pmuthuvel1.appspot.com/eussd/serv",
            success: function (dataTest) {
                var ussdValuesArr = dataTest.ussd;
                loadMainPage(ussdValuesArr);
                alert(firstPageContent);
                $('body').append(firstPageContent);
                $('[data-role=page]').trigger('create');
                $('[data-role=page]').css('display', 'block');
            }, error: function (i, ty, gh) {
            }
        });

    });
</script>

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

"Partially loaded" when document is ready

Is there a way for me to trigger a function once the element identified by #container has finished loading in the DOM? Instead of waiting for the entire DOM to load using document.ready(), I'd like to start populating #container right after it's ...

Using JQuery to call a PHP file and verify a unique identifier

I've been attempting to use this tutorial to check the availability of certain IDs while a user fills out forms. However, I'm working with PostgreSQL instead of MySQL and seem to be encountering issues with my PHP file. There seems to be a small ...

What are the best ways to display nicely formatted JSON data in a text area using React JS?

I am new to React JS and encountered an issue with rendering the pretty JSON data inside a textarea. I'm unsure which part of my code is incorrect, but I want my pretty JSON to be displayed within the textarea as shown below. "email":"<a href="/cd ...

Which internet browsing engine does Android leverage for phonegap applications?

Currently, I'm working on incorporating CSS animations into a phone gap project. Surprisingly, the animations work flawlessly on an iOS device but encounter issues on my Android device. Strangely, elements like dashed borders are not even showing up. ...

Javascript: Anticipating a Return from an Argument

I am currently working on a function that requires an attribute to respond before proceeding with its process. The function call is structured like this : processResult(getResult()); The issue lies in the fact that the getResult function takes some time ...

Toggle the visibility of an element using a checkbox in JavaScript

In my scenario, there are 8 checkboxes where only one is checked by default. If you click on the unchecked checkboxes twice, the table linked to them will hide. Ideally, I want the unchecked checkboxes to be hidden by default and the checked one to be sh ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

Can using display: none impact the SEO of a website's navigation menu?

Is there a difference in SEO impact between using display:none with CSS and using display:none with jQuery for menus? Appreciate the insights! ...

Incorporate an animated loading GIF image within the ajaxStart function, dynamically appending it within a div tag

Is there a way to dynamically display a loading GIF image on all HTML web pages? var loading = $(' <div id="loading"> <img src="../img/loading%20(1).gif" id="loading-image" alt="Loading..." /> </div>'); $(document).ajaxStart( ...

Dynamic Website (Link Relationships / Responsive Design / Content Rendering with CSS and HTML)

Hello everyone! My name is Mauro Cordeiro, and I come from Brazil. I am just diving into the world of coding and have been following various tutorials. Stack Overflow has been an invaluable resource for me in my learning journey! Aside from coding, I am a ...

How can I change the text of a single button by clicking on it without affecting the other buttons that share the same

Currently, I am implementing a posting system where posts can be added using a button. The posts have two additional buttons - one to show/hide content and the other to delete content. I am utilizing jQuery's slideToggle event to toggle the visibility ...

Executing a JQuery click event without triggering a page refresh

I'm dealing with a basic form on a webpage <div class="data-form"> <p>Are you hungry?</p> <form> <label class="radio-inline"><input type="radio" name="optradio" value="yes">Yes</label> ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

How can I efficiently utilize a single piece of code in multiple instances within a jQuery HTML project?

In order to perform 90 calculations similar to the code below, I am looking for a way to streamline the process and reduce the amount of code needed. $(document).ready(function () { $("#btn").click(function () { var v1 = parseInt($("#1val&q ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Create a payment invoice using the power of AJAX, jQuery, PHP, and MySQL

Having issues with my bill calculation. When adding multiple products, the price of all products appears to be the same. I'm unable to calculate the total correctly and struggling to fix this. Please review my code and provide insights. bill.php < ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

Hover effect for changing image source not functioning as anticipated

I'm having issues creating an image that plays a GIF on hover. I came across some jQuery code on this website that should work, but it's not working for me. Any thoughts on what the problem might be? Here is the HTML and JavaScript code: $(doc ...

Retrieving the identifier of a selected division from a dynamically generated collection of divisions using jQuery

I have an HTML structure as shown below. My objective is to extract a clean number from a specific div (id) when clicked and assign it to a variable in jQuery. It should just be a numerical value. PHP is generating this HTML, and I would appreciate any jQ ...

Adding a <tr> tag to an HTML table using JQuery and AJAX in the context of Django framework step by step

I am currently navigating the world of Javascript, Jquery, and Ajax requests and I'm encountering a challenge with how my scripts are executing. My homepage contains a lengthy list of items (over 1200) that need to be displayed. Previously, I loaded ...