user1518003
user1518003

Reputation: 363

dynamically filling <ul></ul> in javascript and php

I have the following element which is empty:

<div data-role="content">
<ul data-role="listview" id="contributionList2" data-inset="true" data-theme="c" data-dividertheme="a">
</ul>
</div> 

I also have a javascript function that has an array called "arrayer" that I'm trying to post to a php script:

for(var i=0;i<arrayer.length;i++){
    $.post('rpc4.php', {'test': arrayer[i] }, function(data){
        $('#contributionList2').append(data);
    });
} 

The javascript code successfully posts the array to the file rpc4.php:

<?php
$myvar = $_POST['test'];
echo '<li>'.$myvar.'</li>';
?>

But when I try to fill the listview "contributionList2" with all of the array elements, it simply displays each one for a second and then replaces it with the next element in the array rather than showing them all in the listview. How can I show all elements from teh array in the listview at once when the javascript code is called?

Upvotes: 0

Views: 345

Answers (1)

Amadan
Amadan

Reputation: 198334

Change html() to append().

html() will replace the content of your <ul> with each pass through your loop; but you want the stuff to accumulate. append() will stuff the new element as the last child of your <ul>.

However, this is not the best way; unless you have a very good reason for it, it would be better if you move your loop serverside: join() your arrayer, post it as a parameter to your PHP script, then explode() it in PHP and generate everything in one go.

Upvotes: 2

Related Questions