Utilizing JQuery to populate DIVs with JSON information

Hey! I recently received some helpful advice from a coding expert, and now I'm in the process of restructuring my code based on these recommendations:

  • When using $.each(), you have the option to return true or false. If you return false, the loop will stop.
  • Avoid building HTML from concatenated strings as it can lead to XSS vulnerabilities. jQuery provides tools to safely build HTML content.
  • In general, try to steer clear of using .html(), especially if you're already working with DOM elements.
  • Absolutely avoid using inline event handlers like onclick. Always look for alternative solutions.

Here is the updated version of the code I'm currently working on:

var page = 1;
$(document).on('click', '#devotionclick', function blogs() {
    $('#postlist').empty();
   //$('#category').prepend('<div class="categories_listing"><span data-type="blogs" data-category="5">Blog Category</span></div>');
    var count = "5";
    var result = $.getJSON('http://howtodeployit.com/api/get_posts/?count=' + count + '&page=' + page, function (data, status) {
        if (data !== undefined && data.posts !== undefined) {
            $.each(data.posts, function (i, item) {    
                var str = item.title;

                $('#postlist').append('<div class="article"' + item.id + '"><div>' + item.title + '</div><div>' + item.excerpt + '</div></div>');
                if (data !== undefined) {
                    $('#stats').text('Page ' + data.query.page + ' of ' + data.pages + ' | Total posts ' + data.count_total + '');
                }
                if (data.query.page < data.pages) {
                    $("#loadmore").show();
                } else {
                    $("#loadmore").hide();
                }
            });
            page++;
        }
    });
    $('#postlist').append('<div id="loadmore"><div id="stats"></div><div id="loadmore">load more</div></div>');
    $('#loadmore').click(blogs);
});

HTML:

!-- Page: home -->
    <div id="home" data-role="page">
        <div class="ui_home_bg" data-role="content"></div>
        <div data-role="listview">
            <a href="#devotion" id="devotionclick" data-role="button">Daily Devotional Messages</a>
        </div><!-- links -->
    </div><!-- page -->

<!-- Page: Daily Devotional Messages -->
    <div id="devotion" data-role="page">
        <div data-role="header" data-position="fixed">
            <h2>Daily Devotional Messages</h2>
        </div><!-- header -->
        <div data-role="content" id="postlist"> </div><!-- content -->
    </div><!-- page -->

Currently, I am facing the following issues:

  1. Upon clicking the button, the first 5 posts load correctly. However, when I click on 'load more,' it loads the next 5 posts instead of appending them to the existing list.

  2. The lists are not displayed as clickable Listview items as expected.

Answer №1

Issue 1
The reason behind the issue is the presence of $('#postlist').empty(); in the click handler.... which clears all elements on the page before loading new ones. Try eliminating this line.

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

Unable to transform moment.js string from specific location to unix time, or any other format

Struggling to convert a datetime string in a different language format to unix time using moment.js. Any tips or workarounds would be greatly appreciated! moment.locale('de'); var c = moment('20.06.2015').format("X"); //getting an Inva ...

Exporting Blender model to three.js CanvasRenderer results in strange distortion of normals

I'm currently experiencing an issue while trying to export a model using the Three.js import/export tool for Blender. Everything works perfectly fine when I use the WebGLRenderer, but when I switch to CanvasRenderer for cross-browser support, the mode ...

Combating React SetState Race Conditions with the Power of Promise.all

componentDidMount() { Promise.all([OfferCreationActions.resetOffer()]).then( () => { OfferCreationActions.updateOfferCreation('viewOnly', true); OfferCreationActions.updateOfferCreation('loadingOffer', true); ...

Stopping videos in the JQuery Cycle Plugin triggers the stop event

Currently, I have a simple cycle set up with YouTube videos using the following code: <script type="text/javascript"> $(document).ready(function () { $('#cycle').cycle({ fx: 'fade', sp ...

Encountering difficulties during the installation of SonataUserBundle on Symfony2 version 2.4

I encountered an issue while trying to install sonata-project/user-bundle with Symfony2 2.4 using Composer. The error message that Composer gives me is as follows: Problem 1 - Conclusion: remove symfony/symfony v2.4.0 - Installation request for ...

CSS First Element

"When an element with a specific id has a first-child descendant that is any of the heading tags (h1, h2, h3, h4, h5, or h6), apply the following CSS styles:" I have come up with the following selector: #content:first-child h1, #content:first-child h2, ...

"Unraveling the serialize() data from an ajax request in PHP: A step

I want to transfer form data to my php using ajax, but I'm facing issues with retrieving it correctly in my php code Here's the Ajax call: $(document).ready(function(){ $('#submit_comm').submit(function(){ let id = 's ...

Is it possible to retrieve a specific element from an array using variable references in Meteor's spacebars?

Within a spacebars template, there is a javascript array called x and an index referred to as i, for example: Template.test.helpers({ 'foo': function() { return { x: ['aa','bb','cc'], ...

Transforming nested arrays using Nifi Jolt to create an array containing custom objects

Struggling to convert nested arrays from JSON input into an array of objects with correct keys and values using Nifi Jolt Transform. The challenge I'm facing is the need to manually specify the column names since they are not evident from the JSON re ...

How to visually deactivate a flat button ( <input type="button"> ) programmatically with JavaScript

I am facing an issue with my buttons. I have one regular button and another flat button created using input elements. After every click, I want to disable the buttons for 5 seconds. The disable function is working properly for the normal button, but for th ...

Utilizing JavaScript: Passing a parameter into a function to be used with getElementById()

Implementing a feature that displays statistics by incrementing rapidly until reaching their final value when the element is in view, creating the illusion of a rising number. Encountering some difficulty in passing the necessary parameters to identify th ...

Retrieving the textbox input and utilizing it as a filename in PHP

Currently, I am facing an issue where I want to use the value of a textbox as the filename for a downloaded file, but I am unsure how to achieve this. While my code successfully downloads the file, it does not allow me to utilize the textbox value as the ...

Enable the image to extend beyond the boundaries of its containing div

How can I prevent a div from extending its width, allowing an image to be visible outside of it in IE8? Specifically, my div may be 200px wide while the image is 250px wide. ...

Designing a sleek border for form input fields

Seeking assistance in finding a solution as my extensive online search has been unsuccessful. Currently, I have this code to style my form labels: label { display:inline-block; height: 15px; width: 350px; float: left; padding: 5px; ...

Transforming JSON object to an array of arrays using JavaScript

Attempting to extract specific values from a JSON object and store them in an array can be quite tricky. Below is an example of what this process might look like: Example: var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]}, "2 ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Utilizing Ajax to Invoke Wordpress Functions from a Client's Browser

Currently working on setting up a WordPress website integrated with WooCommerce, while also developing an HTML5 app for my small online store. I am looking to utilize Ajax to call WordPress functions like search directly from my HTML5 app and receive the r ...

Functionality of JavaScript limited within a form

Here is some HTML code I am working with: <div class = "login"> <form> <input type="text" id="username" name="username" placeholder="Username" style="text-align:center"> <br> <br> <input type="pa ...

There seems to be an issue with XAMPP as I am unable to start my server due to an

A problem has occurred: Apache shut down unexpectedly. 11:58:07 [Apache] This could be caused by a blocked port, missing dependencies, 11:58:07 [Apache] insufficient privileges, a system crash, or another shutdown method. 11:58:07 [Apache] Click on ...

"No data found in the JSON response due to lack of parameters

When I attempted to receive empty parameters, I expected a specific output but instead received a "Cannot Get ..." error message. This is the original code I was using: app.get("/api/timestamp/:date", function(req, res) { let dateString = re ...