Jump to content
mythri

Checking dynamically populated data using ajax with user entered value

Recommended Posts

I am creating a script for creating invoices. Using ajax for populating database data on autosearch. But the products has a field called min_selling_price, user should not be able to put price below min_selling_price. As my entries are dynamic, i am not getting where and how to check it.

Here is my form

<div class="table-responsive">
                             <table class="table table-active table-bordered table-sm">
                             <thead class="thead-active"><tr>
                        <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>  
                            <th>Name</th>
                            <th>Description</th>
                            <th>UOM</th>    
                            <th>Price</th>

                            <th>Qty</th>  

                            <th colspan="2"></th>
                        </tr> </thead> 

                            <tr> 
                      <td><input type='checkbox' class='case'/></td> 
                     <td><input type="text" class="form-control form-control-sm" id="productname_1" name="productname[]" required style="width:120px;"></td> 
                               <input type="hidden" class="form-control" id="productcode_1" name="productcode[]">
                                <td><textarea class="form-control form-control-sm" id="description_1" name="description[]"></textarea></td>


                                <td><select name="uom[]" class="form-control form-control-sm" id="uom_1" style="width:80px;">
                                <option value="">UOM</option>
                                <?php $su1 = mysqli_query($con, "select * from uom");  while($su2 = mysqli_fetch_array($su1)) { 
                                $uoptions .= "<option value='". $su2['uom_name'] . "'>" .$su2['uom_name'] . "</option>";   
                                ?>
                                <option value="<?php echo $su2['uom_name']; ?>"><?php echo $su2['uom_name']; ?></option>
                                <?php
                                }  
                                ?>
                                </select>

                               </td>     
                                <td><input type="text" class="form-control form-control-sm price" required id="price_1" name="price[]"></td>

                                <td><input type="text" class="form-control form-control-sm quantity" required id="quantity_1" name="quantity[]"></td>  

                               <input type="hidden" class="form-control amount" id="amount_1" name="amount[]">

                               <td><button type="button" class='btn btn-danger delete'>-</button></td>
                        <td><button type="button" class='btn btn-success addmore'>+ </button></td>
</tr>  


</table> 
</div>
<script type="text/javascript">

  var options1 = "<?= $uoptions; ?>";
</script>

 <script type="text/javascript" src="js/auto.js"></script>

auto.js

 $(".delete").on('click', function() {
    $('.case:checkbox:checked').parents("tr").remove();
    $('.check_all').prop("checked", false);
    check();
  });
 var i = $('table tr').length - 1;


  $(".addmore").on('click', function() {
    count = $('table tr').length - 1;
    var data = "<tr><td><input type='checkbox' class='case'/></td><td><input class='form-control form-control-sm' type='text' id='productname_" + i + "' name='productname[]' required /></td><input class='form-control' type='hidden' id='productcode_" + i + "' name='productcode[]'/><td> <textarea class='form-control form-control-sm' id='description_"+ i + "' name='description[]'></textarea></td><td><select class='form-control form-control-sm uom' id='uom_" + i + "' name='uom[]'><option value=''>UOM</option>" + options1 + "</select></td><td><input class='form-control form-control-sm price' required type='text' id='price_" + i + "' name='price[]'/></td><td><input class='form-control form-control-sm quantity' required type='text' id='quantity_" + i + "' name='quantity[]'/></td><input class='form-control amount' type='hidden' id='amount_" + i + "' name='amount[]'/></tr>";
    $('table').append(data);
    row = i;
     $('#productname_' + i).autocomplete({
      source: function(request, response) {
        $.ajax({
          url: 'ajax.php',
          dataType: "json",
          method: 'post',
          data: {
            name_startsWith: request.term,
            type: 'items_table',
            row_num: row

          },

          success: function(data) {
            response($.map(data, function(item) {
              var code = item.split("|");

              return {
                label: code[0],
                value: code[0],

                data: item

              }
            }));
          }
        });
      },

     autoFocus: true,
      minLength: 0,
      select: function(event, ui) {
        var names = ui.item.data.split("|");
        id_arr = $(this).attr('id');
        id = id_arr.split("_");
        $('#productcode_' + id[1]).val(names[1]);
        $('#description_' + id[1]).val(names[2]);
        $('#uom_' + id[1]).val(names[3]);
        $('#price_' + id[1]).val(names[4]);
        //$('#tax_' + id[1]).val(names[5]);

      }
    });


    i++;


  });

  function select_all() {
    $('input[class=case]:checkbox').each(function() {
      if ($('input[class=check_all]:checkbox:checked').length == 0) {
        $(this).prop("checked", false);
      } else {
        $(this).prop("checked", true);
      }
    });
  }




  function check() {
    obj = $('table tr').find('span');
    $.each(obj, function(key, value) {
      id = value.id;
      $('#' + id).html(key + 1);
    });
  }

 $('#productname_1').autocomplete({
    source: function(request, response) {
      $.ajax({
        url: 'ajax.php',
        dataType: "json",
        method: 'post',
        data: {
          name_startsWith: request.term,
          type: 'items_table',
          row_num: 1
        },
        success: function(data) {
          response($.map(data, function(item) {
            var code = item.split("|");
            return {
              label: code[0],
              value: code[0],
              data: item
            }
          }));
        }
      });
    },
   autoFocus: true,
    minLength: 0,
    select: function(event, ui) {
      var names = ui.item.data.split("|");
       $('#productcode_1').val(names[1]);
      $('#description_1').val(names[2]);
      $('#uom_1').val(names[3]);
      $('#price_1').val(names[4]);

    }

  });

in ajax.php

if($_POST['type'] == 'items_table'){
    $row_num = $_POST['row_num'];
    $name = $_POST['name_startsWith'];
    $query = "SELECT * FROM items WHERE status='Active' AND name LIKE '".strtoupper($name)."%'";

    $result = mysqli_query($con, $query);
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['name'].'|'.$row['item_id'].'|'.($row['description']).'|'.$row['uom'].'|'.$row['selling_price'].'|'.$row_num;

        array_push($data, $name);   
    }   
    header('Content-Type: application/json');
    echo json_encode($data);
}

in items table, i have a filed 'min_selling_price' , i want to check for each line item whether the user entered price is above , if not it should not allow to proceed. Not getting how to do it?

Share this post


Link to post
Share on other sites

You can do whatever you'd like on the frontend (like return the minimum price with the rest of the data so the UI can perform validation), but you have to verify the data on the backend too. That means making sure you meet two requirements:

1. All necessary information gets passed to the server so that it can determine what that minimum value should be
2. Each piece of information itself also needs to be validated that it is acceptable

Consider this:

Say you pass the form data as well as a hidden input for each minimum price. That does what you need, except it doesn't meet the second requirement: you can't validate that the minimum from the form really is the correct minimum.

Taking a step backwards, instead of the minimum you have the form send the product. Like it's doing. The server will be able to look up the minimum from there, but you also need to validate the product. Which actually you should be doing already, so that shouldn't be surprising.

So in summary: return the minimum through your AJAX so the UI can perform client-side validation, then in your PHP use the product information to look up the minimum value and then re-validate.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.