Nexus1234 Nexus1234 - 1 year ago 96
Ajax Question

PHP generated option list only appearing on first Ajax dynamically generated container

I am having an issue where my php generated select/option list is not applying to all of my dynamically generated blocks/containers. It only adds the PHP select to the last container/block instance, despite being called for each container. When troubleshooting with alerts it seems to run through all of the iterations prior to adding the containers/blocks and generating the select, hence why it always appears on the last only-

n = -1
function addDiv() {
n++;


So, a brief overview - on page initialize the code will get how many entries are in the database within a certain criteria and apply that number to 'length', which then runs the function addDiv() that many times. Usually, when adding a block one at a time via button it will populate the created block with a Select/list of Options via php in the addDiv() function, however when automating this with a loop ( the initialize() function ) the above issue occurs.

$( document ).ready(function() {
initialize();
});

function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);

console.log(arrayJson);
length = arrayJson.length;
console.log(length);

for(var i = 0; i < length; i++) {
addDiv();
};

},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};


here is the addDiv related code with some redactions to make it easier to read.

var n = -1;

function addDiv() {
n++;

$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + n).html(data);
});

$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");

}


and finally here is the contents of the PHP file for generating the option list based off of json data -

<?php
$json = file_get_contents("../ticker/full.json");

$decode = json_decode($json, true);
sort($decode);

echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>


I know this is messy and may require a bit of an in depth read through, so I appreciate anyone taking the time to look.

Is there anything glaringly obvious that can help nudge me in the right direction? I have tried breaking the 'addDiv()' calls within initialize() by wrapping 'addDiv()' with a setTimeout function, but no joy.

Answer Source

it should work with this (I named the arguments differently for comprehension, but index and index_t can all be named n):

var n = -1;

function sendToGenerator(index){
    var index_t = index;
    $.post(  
        "json-option-generator.php",  
        {}                               
    ).done(                          
        function(data)
        {
            $('#selectedcoin' + index_t).html(data); 
        }
    );
}

function addDiv() {
    n++;

    sendToGenerator(n);

    $("<div class='coinmarketcap fill' id='container" 
    + n + 
    "'><form id='"
    + n +
    "' name='"
    + n +
    "' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin" 
    + n + 
    "' name='selectedcoin"
    + n +
    //.etc.....
    "' autocomplete='off' value=''><select></select>").appendTo(".main-container"); 

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download