简体   繁体   中英

Retrieve data from MySQL into dynamically input using PHP & Ajax

I'm building some application which is retrieving data from MySql database into a dynamically inputs using PHP & Ajax when I'm retrieving data for this input it always shown in the next one but it suppose shown in the div that I mentioned in Ajax code.

This picture will explain my problem clearly sorry for my language English is not my first language.

在此处输入图片说明

My html code:

                  <div class="form-group">
                    <label class="control-label col-lg-4"></label>
                      <div class="col-lg-4">
                        <div class="box">
                          <header>
                            <h5>تفاصيل الطلب</h5>
                            </header>
                            <div class="body">
                              <div class="form-group">
                              <label class="control-label col-lg-2">الصنف</label>
                                  <div class="col-lg-10">
                                      <select id="itemname" name="itemname[]" class="form-control">
                                        <option disabled selected>اختر الصنف</option>
                                        <?php echo getValues($pdo); ?>
                                      </select>
                                  </div>
                              </div>
                              <div class="form-group">
                                <label class="control-label col-lg-2">السعر</label>
                                <div class="col-lg-10">
                                  <input type="text" id="price" name="price[]" placeholder="-" readonly class="form-control">
                                </div>
                              </div>
                              <div class="form-group">
                                <label class="control-label col-lg-2">الكمية</label>
                                <div class="col-lg-10">
                                  <input class="form-control" type="text" name="quantity[]" id="quantity" value="0" min="1">
                                </div>
                              </div>
                            </div>
                            </div>
                      </div>
                    </div>

PHP file:

<?php    
    require 'DBConnection.php';
    $code='';
    if(isset($_POST["code"])){
        $id = $_POST["code"];
        $get_c = $pdo->prepare("SELECT * FROM all_menu WHERE `item_name` = '".$id."'");
        $get_c->execute(); 
        while ($row = $get_c->fetch()) {
            $code .= $row['price'];
        }
        echo $code;
    }
?>

JQuery code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var i=1;
    $('#add').click(function(){
    i++;
    $('#append').append('<div class="form-group"><label class="control-label col-lg-4"></label><div class="col-lg-4"><div class="box"><header><h5>تفاصيل الطلب</h5></header><div class="body"><div class="form-group"><label class="control-label col-lg-2">الصنف</label><div class="col-lg-10"><select id="itemname'+i+'" name="itemname[]" class="form-control"><option disabled selected>اختر الصنف</option><?php echo getValues($pdo); ?></select></div></div><div class="form-group"><label class="control-label col-lg-2">السعر</label><div class="col-lg-10"><input type="text" id="price'+i+'" name="price[]" placeholder="-" readonly class="form-control"></div></div><div class="form-group"><label class="control-label col-lg-2">الكمية</label><div class="col-lg-10"><input class="form-control" type="text" name="quantity[]" id="quantity" value="0" min="1"></div></div></div></div></div></div>');
    $('#itemname'+i+'').change(function(){
      var code = $(this).val();  
       $.ajax({
          type: 'POST',
          url: 'pages/GetPrice.php',
          data:{code:code},
          success: function(data){
            document.getElementById("price"+i+"").value = data;
          },
          error: function (jqXHR, textStatus, errorThrown){ 
            alert(errorThrown);
          }
       });
    });
    });
});
</script>

Things like this will get a lot easier, as soon as you let go of that "newbie habit" of always trying to select elements by ID only.

The only thing that is different in all those individual change handler functions you are appending to each new select element, is the ID of the price field you want to write the output into. But you don't need to select that element by ID, there are other ways - in this case, you should "navigate" to it, based on its position in the DOM, in relation to its corresponding select field.

As soon as you do that, this doesn't need X separate handler functions for X separate select fields any more - but just a single one. And if you set it up using event delegation , then you don't need to explicitly add it to each and every new select element you create any more either.

The event delegation part would be something like this:

$(document).on('change', 'name="itemname[]"', function() { ... } );

You do this once , and it will handle change events on all elements with name="itemname[]" anywhere in the document - already existing ones, as well as future ones that will only be added later.

As for the part of finding the matching price field - for that, you simply navigate up from the select field to a common ancestor of the two - in this case, the .body wrapper element should be suitable - and then you look for a price field inside of that element.

The select field the event happened upon can be accessed using $(this) , and to go up and find a specific ancestor element, jQuery provides the parents method - so to access the corresponding price field, you would use something like this:

$(this).parents('.body').find('name="price[]"').val(data);  

Since there are no element IDs involved here any more now, and all element selection happens based on other factors, like the name attribute and position in the DOM, you can completely go without any ...'+i+'... stuff in your element creation. Just don't give those elements any IDs at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM