ajax无法在循环内部工作

时间:2018-08-25 05:42:36

标签: javascript php ajax

我正在创建动态发票样式...如果我选择商品代码,那么它将在我的品牌输入ID中显示该商品代码的商品品牌。如果我添加新商品, 然后我单击加号按钮添加新项目,然后再次选择一个新项目代码2,然后显示该项目代码2的项目brand2 ...因此,此循环在agiain和agian上进行。

我的ajax调用无法正常工作或ajax代码出现错误....我找不到该错误..如果我不使用ajax调用仅显示所选var itemp 的数据,则它显示选定的 brand 中的数据 itemp ,但是使用ajax调用并找到所选数据 itemp brand 无效。请任何人都可以帮助我。

这是我的javascript ajax调用...

function getprods(val) {
        for (j = 1; j <= count; j++) {
            var itemp = $('#item_code' + j).val();
            $.ajax({
                url: 'ajax_getitems.php',
                type: 'POST',
                data: 'state_id=' + itemp,
                dataType: 'json',
                success: function (data) {
                    var len = data.length;
                    if (len > 0) {
                        var id = data[0]['id'];
                        var brand = data[0]['brand'];

                        document.getElementById('brand' + j).value = brand;


                    }

                }
            });
        }
    }

这是我的ajax_getitems.php文件

<?php

include('conn.php');
$model = $_POST['state_id'];
$sql = "SELECT * FROM product WHERE code='$model'";

$result = mysqli_query($conn, $sql);

$users_arr = array();

while ($row = mysqli_fetch_array($result)) {
    $id = $row['id'];
    $brand = $row['brand'];

    $users_arr[] = array("id"    => $id,
                         "brand" => $brand
    );
}

// encoding array to json format
echo json_encode($users_arr);
exit;

?>  

enter image description here

enter image description here

这是我的完整html代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow">
    <link rel="stylesheet" href="css2/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="quotation/jquery-ui.min.css">
    <script src="js2/jquery.min.js"></script>
    <script src="js2/bootstrap.min.js"></script>
    <script src="quotation/js/jquery-ui.js"></script>
    <script src="js2/jquery.dataTables.min.js"></script>
    <script src="js2/dataTables.bootstrap.min.js"></script>
    <link rel="stylesheet" href="css2/dataTables.bootstrap.min.css">
    <style>
      /* Remove the navbar's default margin-bottom and rounded borders */ 
      .navbar {
      margin-bottom: 4px;
      border-radius: 0;
      }
      /* Add a gray background color and some padding to the footer */
      footer {
      background-color: #f2f2f2;
      padding: 25px;
      }
      .carousel-inner img {
      width: 100%; /* Set width to 100% */
      margin: auto;
      min-height:200px;
      }
      .navbar-brand
      {
      padding:5px 40px;
      }
      .navbar-brand:hover
      {
      background-color:#ffffff;
      }
      /* Hide the carousel text when the screen is less than 600 pixels wide */
      @media (max-width: 600px) {
      .carousel-caption {
      display: none; 
      }
      }
    </style>
  </head>
  <body>
    <style>
      .box
      {
      width: 100%;
      max-width: 1390px;
      border-radius: 5px;
      border:1px solid #ccc;
      padding: 15px;
      margin: 0 auto;                
      margin-top:50px;
      box-sizing:border-box;
      }
    </style>
    <link rel="stylesheet" href="css2/datepicker.css">
    <script src="js2/bootstrap-datepicker1.js"></script>
    <script>
      $(document).ready(function(){
        $('#order_date').datepicker({
          format: "yyyy-mm-dd",
          autoclose: true
        });
      });
    </script>
    <script>
    $(document).ready(function(){

            $(document).on('keydown', '.name', function() {

                var id = this.id;
                var splitid = id.split('_');
                var index = splitid[1];

                $( '#'+id ).autocomplete({
                    source: function( request, response ) {
                        $.ajax({
                            url: "getDetails.php",
                            type: 'post',
                            dataType: "json",
                            data: {
                                search: request.term,request:1
                            },
                            success: function( data ) {
                                response( data );
                            }
                        });
                    },
                    select: function (event, ui) {
                        $(this).val(ui.item.label); // display the selected text
                        var userid = ui.item.value; // selected id to input

                        // AJAX
                        $.ajax({
                            url: 'getDetails.php',
                            type: 'post',
                            data: {userid:userid,request:2},
                            dataType: 'json',
                            success:function(response){

                                var len = response.length;

                                if(len > 0){
                                    var id = response[0]['id'];
                                    var phone = response[0]['phone'];
                                    var email = response[0]['email'];
                                    var address = response[0]['address'];
                                    var gst = response[0]['gst'];

                                    document.getElementById('phone').value = phone;
                                    document.getElementById('email').value = email;
                                    document.getElementById('address').value = address;
                                    document.getElementById('gst').value = gst;

                                }

                            }
                        });

                        return false;
                    }
                });
            });


        });

function getproduct(val) {
$.ajax({
url: 'ajax_getproduct.php',
type: 'POST',
data: 'state_id='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var item = data[0]['item'];
var subcat = data[0]['subcat'];
var brand = data[0]['brand'];
var model = data[0]['model'];
var specification = data[0]['specification'];
var unitrate = data[0]['unitrate'];
var unitmesure = data[0]['unitmesure'];

document.getElementById('item').value = item;
document.getElementById('subcat').value = subcat;
document.getElementById('brand').value = brand;
document.getElementById('model').value = model;
document.getElementById('Specification').value = specification;
document.getElementById('unitrate1').value = unitrate;
document.getElementById('unitmesure').value = unitmesure;

}
}
});
}
</script>
    <div class="container-fluid">

      <form method="post" id="invoice_form">
        <div class="table-responsive">
          <table class="table table-bordered">
            <tr>
              <td colspan="2" align="center"><h2 style="margin-top:10.5px">Create Quotation</h2></td>
            </tr>
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-md-8">
                      To,<br />
                        <b>RECEIVER (BILL TO)</b><br />
                        <input type="text" name="name" id="name" class="form-control name" placeholder="Enter Receiver Name" />
                        <textarea name="address" id="address" class="form-control" placeholder="Enter Billing Address"></textarea>
                    </div>
                    <div class="col-md-4">
                      <br />
                      <input type="text" name="phone" id="phone" class="form-control input-sm" placeholder="Phone No." />
                      <input type="text" name="email" id="email" class="form-control input-sm" placeholder="Email" />
                      <input type="text" name="gst" id="gst" class="form-control input-sm" placeholder="GST" />
                    </div>
                  </div>
                  <br />
                  <table id="invoice-item-table" class="table table-bordered">
                    <tr>
                      <th>Sr No.</th>
                      <th>Item Code</th>
                                <th>Brand</th>
                      <th>Model</th>
                      <th>Specification</th>
                      <th>Unit Rate</th>
                      <th>Quantity</th>

                      <th>Actual Amt.</th>
                      <th colspan="2">Discount (%)</th>

                      <th rowspan="2">Total</th>
                      <th rowspan="2"></th>
                    </tr>
                    <tr>
                      <th></th>
                      <th></th>
                      <th></th>

                      <th></th>
                      <th></th>
                      <th>Rate</th>
                      <th></th>
                      <th>Amt.</th>

                    </tr>
                    <tr>
                      <td><span id="sr_no">1</span></td>
                      <td><select type="text" name="item_code[]" id="item_code" class="form-control input-sm"  onChange="getproduct(this.value);" >
                      <option value=""></option>
                      <?php
    include "conn.php";
    $sql = "SELECT * FROM `product`";
    $run = mysqli_query($conn,$sql);

    while($row=mysqli_fetch_array($run))
    {
    ?>
<option><?php echo $row['code']; ?></option>
        <?php } ?>
                      </select>
            <input type="hidden" name="item[]" id="item">
             <input type="hidden" name="subcat[]" id="subcat">
                      </td>
                      <td>
                          <input type="text" name="brand[]" id="brand" class="form-control input-sm" readonly> 
                      </td>

            <td>
              <input type="text" name="model[]" id="model" class="form-control input-sm" readonly>
            </td>
            <td>
              <textarea name="Specification[]" id="Specification" class="form-control" readonly></textarea>
            </td>
               <td><input type="text" name="unitrate[]" id="unitrate1" data-srno="1" class="form-control input-sm unitrate" />
                <input type="hidden" name="unitmesure" id="unitmesure">
               </td>
                      <td><input type="text" name="qty[]" id="qty1" data-srno="1" class="form-control input-sm number_only qty" /></td>

                      <td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount1" data-srno="1" class="form-control input-sm order_item_actual_amount" readonly /></td>
                      <td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate1" data-srno="1" class="form-control input-sm number_only order_item_tax1_rate" /></td>
                      <td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount1" data-srno="1" readonly class="form-control input-sm order_item_tax1_amount" /></td>
                     <td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount1" data-srno="1" readonly class="form-control input-sm order_item_final_amount" /></td>
                      <td></td>
                    </tr>
                  </table>
                  <div align="right">
                    <button type="button" name="add_row" id="add_row" class="btn btn-success btn-xs">+</button>
                  </div>
                </td>
              </tr>
              <tr>
                <td align="right"><b>Total</td>
                <td align="right"><b><span id="final_total_amt"></span></b></td>
              </tr>
              <tr>
                <td colspan="2"></td>
              </tr>
              <tr>
                <td colspan="2" align="center">
                  <input type="hidden" name="total_item" id="total_item" value="1" />
                  <input type="submit" name="create_invoice" id="create_invoice" class="btn btn-info" value="Create" />
                </td>
              </tr>

              <tr>

              </tr>
          </table>
        </div>
      </form>
      <script>

      $(document).ready(function(){
        var final_total_amt = $('#final_total_amt').text();
        var count = 1;


        $(document).on('click', '#add_row', function(){
          count++;

          $('#total_item').val(count);
          var html_code = '';
          html_code += '<tr id="row_id_'+count+'">';
          html_code += '<td><span id="sr_no">'+count+'</span></td>';

         html_code += '<td><select name="item_code[]" id="item_code'+count+'" class="form-control input-sm item_code"><option></option><?php $sql='Select * from product'; $run=mysqli_query($conn,$sql); while($row=mysqli_fetch_array($run)){ echo '<option>'.$row['code'].'</option>'; } ?></select><input type="hidden" name="item[]" id="item'+count+'"><input type="hidden" name="subcat[]" id="subcat'+count+'"></td>';


          html_code += '<td><input type="text" name="brand[]" id="brand'+count+'" class="form-control input-sm" readonly></td>';

          html_code += '<td><input type="text" name="model[]" id="model'+count+'" class="form-control input-sm" readonly></td>';

          html_code += '<td><textarea name="Specification[]" id="Specification'+count+'" class="form-control" readonly></textarea></td>';

          html_code += '<td><input type="text" name="unitrate[]" id="unitrate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only unitrate" /><input type="hidden" name="unitmesure[]" id="unitmesure'+count+'"></td>';

          html_code += '<td><input type="text" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm number_only qty" /></td>';

          html_code += '<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_actual_amount" readonly /></td>';

          html_code += '<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax1_rate" /></td>';

          html_code += '<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax1_amount" /></td>';

          html_code += '<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_final_amount" /></td>';

          html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
          html_code += '</tr>';
          $('#invoice-item-table').append(html_code);
        });

        $(document).on('click', '.remove_row', function(){
          var row_id = $(this).attr("id");
          var total_item_amount = $('#order_item_final_amount'+row_id).val();
          var final_amount = $('#final_total_amt').text();
          var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
          $('#final_total_amt').text(result_amount);
          $('#row_id_'+row_id).remove();
          count--;
          $('#total_item').val(count);
        });





        function cal_final_total(count)
        {
          var final_item_total = 0;
          for(j=1; j<=count; j++)
          {
            var quantity = 0;
            var price = 0;
            var actual_amount = 0;
            var tax1_rate = 0;
            var tax1_amount = 0;
            var tax2_rate = 0;
            var tax2_amount = 0;
            var tax3_rate = 0;
            var tax3_amount = 0;
            var item_total = 0;
            quantity = $('#unitrate'+j).val();
            if(quantity > 0)
            {
              price = $('#qty'+j).val();
              if(price > 0)
              {
                actual_amount = parseFloat(quantity) * parseFloat(price);
                $('#order_item_actual_amount'+j).val(actual_amount);
                tax1_rate = $('#order_item_tax1_rate'+j).val();
                if(tax1_rate > 0)
                {
                  tax1_amount = -(parseFloat(actual_amount)*parseFloat(tax1_rate)/100);
                  $('#order_item_tax1_amount'+j).val(tax1_amount);
                }

                item_total = parseFloat(actual_amount) + parseFloat(tax1_amount) + parseFloat(tax2_amount) + parseFloat(tax3_amount);
                final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
                $('#order_item_final_amount'+j).val(item_total);
              }
            }
          }
          $('#final_total_amt').text(final_item_total);
        }

function getprods()
{
 for(j=1; j<=count; j++)
{
var itemp = $('#item_code'+j).val();
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: 'state_id='+itemp,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var brand = data[0]['brand'];

document.getElementById('brand'+j).value = brand;


}

}
});
}
}


        $(document).on('blur', '.qty', function(){
          cal_final_total(count);
        });

        $(document).on('blur', '.order_item_tax1_rate', function(){
          cal_final_total(count);
        });

         $(document).on('change', '.item_code', function(){
              getprods(this.value);
        });



        $('#create_invoice').click(function(){
          if($.trim($('#order_receiver_name').val()).length == 0)
          {
            alert("Please Enter Reciever Name");
            return false;
          }

          if($.trim($('#order_no').val()).length == 0)
          {
            alert("Please Enter Invoice Number");
            return false;
          }

          if($.trim($('#order_date').val()).length == 0)
          {
            alert("Please Select Invoice Date");
            return false;
          }

          for(var no=1; no<=count; no++)
          {
            if($.trim($('#item_name'+no).val()).length == 0)
            {
              alert("Please Enter Item Name");
              $('#item_name'+no).focus();
              return false;
            }

            if($.trim($('#unitrate'+no).val()).length == 0)
            {
              alert("Please Enter Quantity");
              $('#unitrate'+no).focus();
              return false;
            }

            if($.trim($('#qty'+no).val()).length == 0)
            {
              alert("Please Enter Price");
              $('#qty'+no).focus();
              return false;
            }

          }

          $('#invoice_form').submit();

        });

      });
      </script>



<script>
$(document).ready(function(){
$('.number_only').keypress(function(e){
return isNumbers(e, this);      
});
function isNumbers(evt, element) 
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) &&      // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});


</script>
  </body>
</html>


<?php
include('conn2.php');
if(isset($_POST['create_invoice']))
{
  $order_receiver_name=$_POST['order_receiver_name'];
  $order_receiver_address=$_POST['order_receiver_address'];
  $order_no=$_POST['order_no'];
  $order_date=$_POST['order_date'];

  $order_total_before_tax = 0;
  $order_total_tax1 = 0;
  $order_total_tax2 = 0;
  $order_total_tax3 = 0;
  $order_total_tax = 0;
  $order_total_after_tax = 0;

  date_default_timezone_set('Asia/Kolkata');
    $current = date('d-m-Y H:i:s');

  $sql = "INSERT INTO `tbl_order`(`order_no`, `order_date`, `order_receiver_name`, `order_receiver_address`, `order_total_before_tax`, `order_total_tax1`, `order_total_tax2`, `order_total_tax3`, `order_total_tax`, `order_total_after_tax`, `order_datetime`) VALUES ('$order_no','$order_date','$order_receiver_name','$order_receiver_address','$order_total_before_tax','$order_total_tax1','$order_total_tax2','$order_total_tax3','$order_total_tax','$order_total_after_tax','$current')";

  $run = mysqli_query($conn, $sql);

  if($run)

      {
          echo "<script>alert('Inserted Successfully')</script>";
      }
      else{
          echo("Error description: " . mysqli_error($conn));
      }

 $last_id = mysqli_insert_id($conn);

  for($count=0; $count<$_POST["total_item"]; $count++)
  {
    $item_name =  $_POST['item_name'][$count];
    $unitrate =  $_POST['unitrate'][$count];
    $qty =  $_POST['qty'][$count];
    $order_item_actual_amount =  $_POST['order_item_actual_amount'][$count];
    $order_item_tax1_rate =  $_POST['order_item_tax1_rate'][$count];
    $order_item_tax1_amount =  $_POST['order_item_tax1_amount'][$count];
    $order_item_tax2_rate =  $_POST['order_item_tax2_rate'][$count];
    $order_item_tax2_amount =  $_POST['order_item_tax2_amount'][$count];
    $order_item_tax3_rate =  $_POST['order_item_tax3_rate'][$count];
    $order_item_tax3_amount =  $_POST['order_item_tax3_amount'][$count];
    $order_item_final_amount =  $_POST['order_item_final_amount'][$count];

    $sql2 = "INSERT INTO `tbl_order_item`(`order_id`, `item_name`, `order_item_quantity`, `order_item_price`, `order_item_actual_amount`, `order_item_tax1_rate`, `order_item_tax1_amount`, `order_item_tax2_rate`, `order_item_tax2_amount`, `order_item_tax3_rate`, `order_item_tax3_amount`, `order_item_final_amount`) VALUES ('$last_id','$item_name','$order_item_quantity','$order_item_price','$order_item_actual_amount','$order_item_tax1_rate','$order_item_tax1_amount','$order_item_tax2_rate','$order_item_tax2_amount','$order_item_tax3_rate','$order_item_tax3_amount','$order_item_final_amount')";

    $run2 = mysqli_query($conn, $sql2);

  if($run2)

    {
      echo "<script>alert('inserted successfully')</script>";
    }
    else{
      echo("Error description: " . mysqli_error($conn));
    }

    $order_total_before_tax = $order_total_before_tax + floatval(trim($_POST["order_item_actual_amount"][$count]));

        $order_total_tax1 = $order_total_tax1 + floatval(trim($_POST["order_item_tax1_amount"][$count]));

        $order_total_tax2 = $order_total_tax2 + floatval(trim($_POST["order_item_tax2_amount"][$count]));

        $order_total_tax3 = $order_total_tax3 + floatval(trim($_POST["order_item_tax3_amount"][$count]));

        $order_total_after_tax = $order_total_after_tax + floatval(trim($_POST["order_item_final_amount"][$count]));



  }
  $order_total_tax = $order_total_tax1 + $order_total_tax2 + $order_total_tax3;

  $sql3 = "UPDATE `tbl_order` SET `order_total_before_tax`='$order_total_before_tax',`order_total_tax1`='$order_total_tax1',`order_total_tax2`='$order_total_tax2',`order_total_tax3`='$order_total_tax3',`order_total_tax`='$order_total_tax',`order_total_after_tax`='$order_total_after_tax' WHERE `order_id`='$last_id'";

  $run3 = mysqli_query($conn, $sql3);

  if($run3)

    {
      echo "<script>alert('inserted successfully')</script>";
    }
    else{
      echo("Error description: " . mysqli_error($conn));
    }
}


?>

3 个答案:

答案 0 :(得分:1)

按如下所示编辑您的php文件。

result.map.with_object({}) { |h, new_h| new_h[h[:label]] = h[:value] }

然后按如下所示编辑ajax部分

<?php
include('conn.php');
$model = $_POST['state_id'];
$sql = "SELECT * FROM product WHERE code='$model'";
$result = mysqli_query($conn, $sql);

// encoding array to json format
echo json_encode($result);
exit;
?> 

答案 1 :(得分:0)

j <= count;

但是'count'var在哪里?

答案 2 :(得分:0)

在 ajax 中添加属性 async: false 可以解决这个问题。

 $.ajax({
          url:"get_response_filter.php",
          method: "POST",
          dataType: 'json',
          async: false,