1

I have a HTML form for products which contains initially a fields group (for the product components) of 2 rows and can add rows using a button with an onClick event to a js function addRow(). the code is:

<?php
                $arrayNumber = 0;
                for($x = 1; $x < 3; $x++) { ?>
                    <tr id="editRow<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">                          
                        <td style="padding-left:20px;padding-right: 20px;">
                            <div class="form-group">
                            <select class="form-control" name="editRawName[]" id="editRawName<?php echo $x; ?>" onchange="getRawData(<?php echo $x; ?>)">
                                <option value="">~~SELECT~~</option>
                                <?php
                                    $rawSql = "SELECT * FROM raw_material WHERE status = 1";
                                    $rawData = $connect->query($rawSql);

                                    while($row = $rawData->fetch_array()) {                                         
                                        echo "<option value='".$row['raw_id']."' id='changeRaw".$row['raw_id']."'>".$row['raw_name']."</option>";
                                        } // /while 

                                ?>
                            </select>
                            </div>
                        </td>
                        <td style="padding-left:20px;">
                            <div class="form-group">
                            <input type="number" name="editQuantity[]" id="editQuantity<?php echo $x; ?>"  autocomplete="off" class="form-control" min="1"/>
                            </div>
                        </td>
                        <td>

                            <button class="btn btn-default removeRawRowBtn" type="button" id="removeRawRowBtn" onclick="removeRawRow(<?php echo $x; ?>)"><i class="glyphicon glyphicon-trash"></i></button>
                        </td>
                    </tr>
                <?php
                $arrayNumber++;
                } // /for?>

Now, to edit a product I use a js function editProduct() to fetch the selected product data and return it as a JSON response to fill the product form fields. The editProduct function code part to grab and fill product fields is:

function editProduct(productId = null) {

if(productId) {
    $("#productId").remove();
    $(".text-danger").remove();
    $(".form-group").removeClass('has-error').removeClass('has-success');
    $('.div-loading').removeClass('div-hide');
    $('.div-result').addClass('div-hide');

    $.ajax({
        url: 'action.php',
        type: 'post',
        data: {productId: productId},
        dataType: 'json',
        success:function(response) {
            $('.div-loading').addClass('div-hide');
            $('.div-result').removeClass('div-hide');

            $(".editProductFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.product_id+'" />');

            // product name
            $("#editProductName").val(response.product_name);
            // category name
            $("#editCategoryName").val(response.categories_id);
            // quantity
            $("#editProductQuantity").val(response.quantity);
            // product unit
            $("#editProductUnit").val(response.product_unit);
            // sales margin
            $("#editSalesMargin").val(response.sales_margin);
            // status
            $("#editProductStatus").val(response.status);
            // Get the product components count
            var totalComponents = response.total_components;
            // Loop for every component
            // Set the fields id that will contains the data
            // Fill the fields with data
            for (var x = 0; x<totalComponents; x++){

                var idrawn = "#editRawName"+x.toString();
                var idrawq = "#editQuantity"+x.toString();
                var resri = "raw_id_"+x.toString();
                var resqu = "rp_quantity_"+x.toString();
            $(idrawn).val(response[resri]);
            $(idrawq).val(response[resqu]);
            }

The problem is: In case of a product with a total components of more than 2, I need to add rows to be filled with the components data. First, I tried to launch the addRow() function before the last for loop in the editProduct function like this (didn't work):

if (totalComponents > 2) {
                var adro = totalComponents - 2;
                for (var y=0; y<adro; y++)
                { addRow(); }
            }

Then, I tried to simulate the click of the Add Component button that launch the addRow function using the solution posted here: How to simulate a click with JavaScript? and change the above code like this:

if (totalComponents > 2) {
                var adro = totalComponents - 2;
                for (var y=0; y<adro; y++)
                { eventFire(document.getElementById('addRowBtn'), 'click'); }
            }

but still no luck. The code of addRow function is:

function addRow() {
$("#addRowBtn").button("loading");
var tableLength = $("#rawTable tbody tr").length;
var tableRow;
var arrayNumber;
var count;

if(tableLength > 0) {
    tableRow = $("#rawTable tbody tr:last").attr('id');
    arrayNumber = $("#rawTable tbody tr:last").attr('class');
    count = tableRow.substring(3);
    count = Number(count) + 1;
    arrayNumber = Number(arrayNumber) + 1;
} else {
    // no table row
    count = 1;
    arrayNumber = 0;
}

$.ajax({
    url: 'action1.php',
    type: 'post',
    dataType: 'json',
    success:function(response) {
        $("#addRowBtn").button("reset");
        var tr = '<tr id="row'+count+'" class="'+arrayNumber+'">'+
            '<td style="padding-left:20px;padding-right: 20px;">'+
                '<div class="form-group">'+

                '<select class="form-control" name="rawName[]" id="rawName'+count+'" onchange="getRawData('+count+')" >'+
                    '<option value="">~~SELECT~~</option>';
                    $.each(response, function(index, value) {
                        tr += '<option value="'+value[0]+'">'+value[1]+'</option>';
                    });
                tr += '</select>'+
                '</div>'+
            '</td>'+
            '<td style="padding-left:20px;">'+
                '<div class="form-group">'+
                '<input type="number" name="quantity[]" id="quantity'+count+'" autocomplete="off" class="form-control" min="1" />'+
                '</div>'+
            '</td>'+
            '<td>'+
                '<button class="btn btn-default removeRawRowBtn" type="button" onclick="removeRawRow('+count+')"><i class="glyphicon glyphicon-trash"></i></button>'+
            '</td>'+
        '</tr>';
        if(tableLength > 0) {
            $("#rawTable tbody tr:last").after(tr);
            $("#totalComponents").remove();
            var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+count+'" />';
        } else {
            $("#rawTable tbody").append(tr);
            $("#totalComponents").remove();
            var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+tableLength+'" />';
        }
        $("#rawTable").after(comp);
    }
});}

I was wandering if there is a way to get the result that I need.

Ahmedev
  • 11
  • 3
  • When you say those two attempts "didnt work" ... what exactly didn't work? Did they not add a row? Did they do nothing at all? Did they add a row but got errors? – IncredibleHat Jun 25 '18 at 13:24
  • they just did nothing and no errors was returned – Ahmedev Jun 25 '18 at 13:31
  • Interesting. Unsure why absolutely no row would be added, AND no errors... odd indeed. Must be missing something simple somewhere. As a side question... is there a specific reason you call php with ajax for each row added? It seems all it returns is the options list (which should be the same for every row). Couldn't you generate that options list as a hidden variable on the initial php page output build? Would save all those ajax calls, and make the js a little cleaner in addRow. – IncredibleHat Jun 25 '18 at 13:34
  • Plus with doing addRow multiple times at once, the ajax may be clobbering the same `count` value since one may not have returned and added to the table before the other one fired off and so forth. – IncredibleHat Jun 25 '18 at 13:36
  • I'm using ajax to not refresh the page when the edit request is made. Plus I show the edit form in popup modal. – Ahmedev Jun 25 '18 at 13:45
  • Right, but those options are static (they dont change between each click of addRow, right?) You can save yourself a headache of js .promises by making the options a static variable in the original generation of the page content (even if its in a modal). Because you see you are already doing a `for` and `mysql` search (each time, in the loop which is excessive)... you can just generate that list of options as a hidden variable in the original edit form page. :) Then you can eliminate the entire ajax requirement inside `addRow`. – IncredibleHat Jun 25 '18 at 13:49
  • Sorry, I still cannot see why addRow is not adding a row when you try to fire it off in the editProduct function :( Something... odd. – IncredibleHat Jun 25 '18 at 13:51
  • When I tried the addRow call, the php script in the ajax call runs the correct amounts of times but still didn't show the rows I need. – Ahmedev Jun 25 '18 at 14:05

0 Answers0