Question

I have a javascript file posting data to php files which are suppose to get data from a mysql database, then populate fields with specified data. When I call the php function to store the names of the fields in the database, it returns a hidden field with how many fields are in the table stored as the value to the hidden field:

$i = 0;
$field_names = [];    

while($i < mysql_num_fields($request)){
    $field = mysql_fetch_field($request, $i);
    $field_names[] = $field->name;

    if(!$field){
        die('something is wrong with the field var');
    };

    echo('<div class="fields" id="field_' . $i . '">' . $field->name . '<br /></div>');
        $i++;
};

    echo('<input type="hidden" value="' . $_POST['postselecttbl'] . '" id="hidden_tbl" />' .
         '<input type="hidden" value="' . count($field_names) . '" id="num_fields" />');

    $_SESSION['field_names'] = $field_names;

Everything appears to work. The hidden field '#num_fields' gets set with how many fields there are. But when I get the val() of '#num_fields' with jquery, it returns undefined until you run the function again, then it has the value from the previous time it was ran.

$.post('php/get_flds.php', {postdbhost: dbhost, postdbuser: dbuser, postdbpass: dbpass, postselectdb: selectdb, postselecttbl: selecttbl},
    function(d){
        $('#display_out').html(d);
    }
);

var num_flds = $('#num_fields').val();

alert('about to pop ' + num_flds);

for(var i = 0; i < num_flds; i++){
    alert('populating ' + i);
    pop_fld(i);
};

Is the hidden input not being set correctly? I mean, it shows in the html code as being set, but jquery is not cooperating.

Was it helpful?

Solution

Is this hidden field called from ajax request? If so then try following:

$.post('php/get_flds.php', {postdbhost: dbhost, postdbuser: dbuser, postdbpass: dbpass, postselectdb: selectdb, postselecttbl: selecttbl},
    function(d){
        $('#display_out').html(d);
        var num_flds = $('#num_fields').val();

        alert('about to pop ' + num_flds);

        for(var i = 0; i < num_flds; i++){
             alert('populating ' + i);
             pop_fld(i);
        };
    }
);

Otherwise the jquery doesn't know the value yet as this DOM is not in the document yet.

OTHER TIPS

Post is an asynchronous call I think. var num_fields is set BEFORE post request ends and you should update it's value when post is done. Try something like :

var num_flds = $('#num_fields').val();
$.post('php/get_flds.php', {postdbhost: dbhost, postdbuser: dbuser, postdbpass: dbpass, postselectdb: selectdb, postselecttbl: selecttbl},
    function(d){
        $('#display_out').html(d);
        num_fields = $('#num_fields').val();
    }
);



alert('about to pop ' + num_flds);

for(var i = 0; i < num_flds; i++){
    alert('populating ' + i);
    pop_fld(i);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top