Rows().every() with ajax request inside

Rows().every() with ajax request inside

jstevejsteve Posts: 2Questions: 1Answers: 0
edited July 2019 in Free community support

Hello,

i'm trying to update an input fields inside of datatable on each row, but first i take a value from a cell and send it to ajax to get a value and then update de input field with this value.

the principal problem es that rows().every() is executed more fast than ajax and just one row is updated.

here is the code that i'm using:

//CALL THE FUNCTION

updatePrices(0.95); 

function updatePrices(freight){

     table.rows().every(function () {
       var sk = table.cell(this,2).data(); // HERE I GET THE VALUE OF DATTABLES TO SEARCH THE PRODUCT AND ITS PRICE.
                
       var dataString = 'sku='+ sk;

        $.ajax({
            type: "POST",
            url: "searchProductBySku.php",
            data: dataString,
            dataType: 'json',
            cache: false,
            success: function(data){
               newprice = parseFloat(data[9])+parseFloat(freight);// RETURN NEW PRICE AND SUM THE FREIGHT COST

               table.cell(this,9).invalidate().nodes().to$().find('input').val(parseFloat(newprice).toFixed(2)); // AND CELL WITH INPUT IS UPDATED
                    
             } 
          });
       });
      alert('Prices were updated, please check them before send this order.');
}

any one knows a better way to complete this function? or any help it is welcome

thank you.

Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    Hi @jsteve ,

    I suspect the problem is because the this on line 21 is being changed by the time the ajax response gets back, so only the final row is being updated.

    Could you try this for the success() function instead,

                success: function(data){
                  var that = this;
                   newprice = parseFloat(data[9])+parseFloat(freight);// RETURN NEW PRICE AND SUM THE FREIGHT COST
     
                   table.cell(that,9).invalidate().nodes().to$().find('input').val(parseFloat(newprice).toFixed(2)); // AND CELL WITH INPUT IS UPDATED
                         
                 }
    

    Cheers,

    Colin

  • jstevejsteve Posts: 2Questions: 1Answers: 0

    Hi Colin thanks for your help.

    the changes doesn't work, i think is caused by rows()every() is fastest than ajax response, rows().every() finish while ajax response is just executed the first time

    even i tried with callback function to wait until ajax finish each iteration but rows().every() keep ignoring and finishing first.

    i will try storing the sku and the index row in array and then run a loop inside this array, exec the ajax and update the row with the index stored

This discussion has been closed.