List items are loaded dynamically in an unordered fashion

I have been working on a jquery slider using flickerplate. Below is the code that works when the values are hardcoded:

<div class="flicker-example">

    <ul>
            <li data-background="lib/flicker-1.jpg">
            <div class="flick-title">Promo 1</div>
            <div class="flick-sub-text">25$ OFF FLAT !! Limited Offer!</div>
        </li>

        <li data-background="lib/flicker-2.jpg">
            <div class="flick-title">Promo 2</div>
            <div class="flick-sub-text">Bumper Sale !! Buy 1 Get 1 Free !!</div>
        </li>           
    </ul>
</div>

My goal is to load the content using a JSON array. Here is the code I have written:

<div class="flicker-example">
    <ul>
       <script type='text/javascript'>
        $(document).ready(function(){
                $.getJSON('http://testdb2.weby.biz/deallist.php', function(data) {
                        $.each(data, function(key, val) {
                            $(".flicker-example ul").append('<li data-background="'+ val.Product_Variant_Image + '"><div class="flick-title">' + val.Product_Brand_Name + '</div><div class="flick-sub-text">' + val.Product_Variant_Name + '</div></li>');
                        });
                });

        });
        </script>
    </ul>
</div>

I am having trouble making the dynamically loaded content work like the hardcoded one. Any help would be greatly appreciated. Thank you!

Answer №1

It seems like the plugin initialization occurs when the DOM is loaded. It's possible that you have code that resembles this:

$(document).ready(function() {
    $('.flicker-example').flickerplate();
});

This code works well when the content is static HTML because it is present when the code runs. However, in your case, you are loading JSON data asynchronously, so the sequence of events is as follows:

  1. DOM ready
  2. Flickerplate initialized
  3. JSON AJAX request sent
  4. JSON response received
  5. HTML generated

You actually want step 2 to occur last, after step 5, so you need to modify the callback function for your $.getJSON call:

$(document).ready(function(){
    $.getJSON('http://example.com/data.json', function(data) {
        $.each(data, function(key, val) {
            $(".flicker-example ul").append('<li data-background="'+ val.image + '"><div class="flick-title">' + val.brand + '</div><div class="flick-sub-text">' + val.variant + '</div></li>');
        });
        $('.flicker-example').flickerplate(); // initiate the plugin after the HTML elements are in place
    });
});

Answer №2

Experiment with this: Implement CORS (Cross-Origin Request) on your server. Here's an example for Apache in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

Alternatively, you can use this code snippet in PHP:

 header("Access-Control-Allow-Origin: *");

Answer №3

<?php

$checkLogin = file_get_contents("http://testdb2.weby.biz/deallist.php");

// Removing unwanted characters
for ($i = 0; $i <= 31; ++$i) { 
    $checkLogin = str_replace(chr($i), "", $checkLogin); 
}
$checkLogin = str_replace(chr(127), "", $checkLogin);

// Handling the beginning of the file
if (0 === strpos(bin2hex($checkLogin), 'efbbbf')) {
   $checkLogin = substr($checkLogin, 3);
}

//$checkLogin = json_decode( $checkLogin );
//print_r($checkLogin);

?>




<div class="flicker-example">
    <ul>
       <script type='text/javascript'>
        $(document).ready(function(){
                    /* calling the php file that contains the json_encoded php array */
                //$.getJSON('http://testdb2.weby.biz/deallist.php', function(data) {
            //alert(JSON.stringify(data));
                        /* data will contain the php array as a javascript object */
        $.each(<?php echo $checkLogin; ?>, function(key, val) {
                            $(".flicker-example ul").append('<li data-background="'+ val.Product_Variant_Image + '"><div class="flick-title">' + val.Product_Brand_Name + '</div><div class="flick-sub-text">' + val.Product_Variant_Name + '</div></li>');
                        });
                //});

        });
        </script>
    </ul>
</div>

More information available at: json_decode returns JSON_ERROR_SYNTAX but online formatter says the JSON is OK

Answer №4

If the data in your array is formatted correctly like this:

arr[0]
Object {title: "Special Deal 1", text: "50% OFF Today Only!"}
arr[1]
Object {title: "Special Deal 2", text: "2 for the Price of 1!"}

Then take a look at this demo:

http://jsfiddle.net/m6o3nyt8/1/

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

Restrict the height of posts created in the summernote editor

My goal is to create a structured page application using summernote. When using summernote, a div with contenteditable=true is appended to the body to allow users to add content. However, I want to set a fixed height for this div so that users can only ent ...

Using JavaFX to create a TreeTableView with nodes of varying sizes

I need assistance with styling TreeTableViews and their rows. I have set up a treetableview showcasing objects named Component, divided into classes A, B, and C. In my setup, B objects are nested within A, and C objects are nested within B objects. While I ...

Transform JSON data into a dropdown menu using select and option elements

I'm currently working on decoding the code snippet below: $options = Input::get('options'); $product->options = json_encode($options); I am attempting to display this within a select/option dropdown, but when I try to decode it using ...

Utilizing jQuery to Adjust Tab Transparency

I'm trying to add some opacity to my jQuery tabs, but so far I've only been successful with accordions. Any tips or tricks for achieving this effect with tabs? Styling with CSS .ui-tabs{ background-image: none; background: rgba(204, 204 ...

Is it possible to adjust the color of this AnchorLink as I scroll down?

Currently struggling to update the color of a logo as I scroll. While the navigation bar successfully changes colors, the logo remains stagnant. Here is the excerpt from my existing code: navigation.js return ( <Nav {...this.props} scrolled={this ...

What is the process for generating a null result cursor upon publication?

Is it possible to return an empty cursor in Meteor? Meteor.publish('example', function(id) { check(id, Match.Maybe(String)) if (!this.userId) return [] }) Although I want the publication to return an empty result when the user is not lo ...

Hiding the y-axis on a msstackedcolumn2dlinedy Fusion Chart: A step-by-step guide

Currently, I am utilizing the msstackedcolumn2dlinedy fusion charts. To see an example of this in action, please take a look at this fiddle: Fiddle The objective I have is to hide the y-axis value on the right side of this chart. Can anyone provide guida ...

Click the button to dynamically add a Bootstrap select element

I need assistance creating a select element with a Bootstrap class using a button click event. The element is successfully inserted into the body, but it does not appear on the page. https://i.sstatic.net/ppHfL.png <html> <head> <link re ...

Laravel and Vue: Retrieve complex data with multiple relationships

In my data model, I have a concept of Exercise which is linked to Topic, and Topic is associated with Subject. By using the code snippet below: Exercise::with('topic')->get() I can easily access the properties of the current topic within Vu ...

Using VB.NET with Selenium to locate and interact with dropdown elements

My knowledge of selenium is limited, and I'm facing difficulty in selecting an element from a dropdown menu on AliExpress using vb.net. The issue arises when the driver either fails to locate the intended element or finds another element with the same ...

Optimizing web content for iOS Safari with min-height media queries

I'm currently working on a Bootstrap-based photo browser that needs to have a responsive 4:3 aspect ratio. To achieve this, I have implemented the following approach: #carousel { width: 320px; height: 240px; ... } Additionally, I utilize media ...

When working with Node.JS, is it necessary to include 'event' if you include 'net' using the require statement?

As I examine the code, I notice that there is no instance of "require('event')" present. However, there is this piece of code: server.on('error', function (e) { if (e.code == 'EADDRINUSE') { console.log('Address in ...

How can I pass an object into EJS templates from views in Express 3.x?

Currently, I am utilizing ejs templates in combination with node.js and express 3.x. Is there a way to display the data object that is passed into the view? Can it be achieved similar to this example in index.ejs: <%= dump(session) %> ...

"Having trouble with jQuery datepicker in Ruby on Rails? It seems to only function properly after

Whenever I navigate through the form page and click on the date_sent text field, jQuery should open a datepicker. However, initially nothing happens, but when I refresh the page it works. I suspect that my issue is related to turbolinks, as I believe that ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Guide to transforming a random hash into a visually appealing HTML table

After exploring HTML::QuickTable, I've noticed that it seems to only support a one-level-deep hash. I couldn't find a way within this module to specify the colspan and rowspan for certain headers when dealing with a multi-level hash structure. Is ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Minimize the gaps between items within a CSS grid design

I'm struggling with adjusting the whitespace between 'Job Role' and 'Company Name' in my grid layout. Here's a snippet of what I have: https://i.sstatic.net/l55oW.png The container css is set up like this: .experience-child ...

What is the procedure for transforming a JSON response into an array?

In my JSON response, I would like the values to be listed instead of appearing as a comma-separated single line. Here is a snippet of my code: URL url = new URL(urlStr); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMeth ...

Having trouble with ion-item click not functioning in Ionic 3?

Working on my Ionic 3 project, I have encountered an issue with the ion-item click listener. The scenario is that I am adding text over a canvas and then attempting to change the style of the text (such as font-family, font-size, bold, and italic). The UI ...