如何修改代码以使用我的数据库

时间:2015-05-05 16:29:38

标签: javascript sql ajax pdo

新规范(不工作):

(index.php):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Workorder System</title>

    <!-- Bootstrap core CSS -->
    <link href="css/jquery-ui.min.css" rel="stylesheet">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/datepicker.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/sticky-footer-navbar.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>


    <!-- Begin page content -->
    <div class="container content">
        <div class='row'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
                <h1 class="text-center title">Workorder System </h1>
            </div>
        <h2>&nbsp;</h2>
        <div class='row'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
                            <th width="15%">Model #</th>
                            <th width="38%">Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input class="case" type="checkbox"/></td>
                            <td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_1" class="form-control autocomplete_txt" autocomplete="off"></td>
                            <td>
                            <input type="text" data-type="model" name="modelName[]" id="modelName_1" class="form-control autocomplete_txt" autocomplete="off">
                            </td>
                            <td>
                            <input type="text" data-type="category" name="category[]" id="categoryName_1" class="form-control autocomplete_txt" autocomplete="off">
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class='row'>
            <div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
                <button class="btn btn-danger delete" type="button">- Delete</button>
                <button class="btn btn-success addmore" type="button">+ Add More</button>
            </div>

            <div class='col-xs-12 col-sm-offset-4 col-md-offset-4 col-lg-offset-4 col-sm-5 col-md-5 col-lg-5'>
                <form class="form-inline">
                    <div class="form-group">
                        <label>Subtotal: &nbsp;</label>
                        <div class="input-group">
                            <div class="input-group-addon">$</div>
                            <input type="number" class="form-control" id="subTotal" placeholder="Subtotal" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Tax: &nbsp;</label>
                        <div class="input-group">
                            <div class="input-group-addon">$</div>
                            <input type="number" class="form-control" id="tax" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Tax Amount: &nbsp;</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="taxAmount" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
                            <div class="input-group-addon">%</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Total: &nbsp;</label>
                        <div class="input-group">
                            <div class="input-group-addon">$</div>
                            <input type="number" class="form-control" id="totalAftertax" placeholder="Total" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Amount Paid: &nbsp;</label>
                        <div class="input-group">
                            <div class="input-group-addon">$</div>
                            <input type="number" class="form-control" id="amountPaid" placeholder="Amount Paid" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Amount Due: &nbsp;</label>
                        <div class="input-group">
                            <div class="input-group-addon">$</div>
                            <input type="number" class="form-control amountDue" id="amountDue" placeholder="Amount Due" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <h2>Notes: </h2>
        <div class='row'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
                <div class="form-group">
                    <textarea class="form-control" rows='5' id="notes" placeholder="Your Notes"></textarea>
                </div>
            </div>
        </div>      
    </div>

    <script src="js/jquery.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/bootstrap-datepicker.js"></script>
    <script src="js/auto.js"></script>
  </body>
</html>

(auto.js):

//adds extra table rows
var i=$('table tr').length;
$(".addmore").on('click',function(){
    html = '<tr>';
    html += '<td><input class="case" type="checkbox"/></td>';
    html += '<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="model" name="modelName[]" id="modelName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="category" name="category[]" id="categoryName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '</tr>';
    $('table').append(html);
    i++;
});

//to check all checkboxes
$(document).on('change','#check_all',function(){
    $('input[class=case]:checkbox').prop("checked", $(this).is(':checked'));
});

//deletes the selected table rows
$(".delete").on('click', function() {
    $('.case:checkbox:checked').parents("tr").remove();
    $('#check_all').prop("checked", false); 
    calculateTotal();
});

//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
    type = $(this).data('type');

    if(type =='productCode' )autoTypeNo=0;
    if(type =='model' )autoTypeNo=1;    

    $(this).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                method: 'post',
                data: {
                   name_startsWith: request.term,
                   type: type
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[autoTypeNo],
                            value: code[autoTypeNo],
                            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("_");
            $('#itemNo_'+id[1]).val(names[0]);
            $('#modelName_'+id[1]).val(names[1]);
            $('#cateogryName_'+id[1]).val(names[1]);
            calculateTotal();
        }               
    });
});

//price change
$(document).on('change keyup blur','.changesNo',function(){
    id_arr = $(this).attr('id');
    id = id_arr.split("_");
    quantity = $('#quantity_'+id[1]).val();
    price = $('#price_'+id[1]).val();
    if( quantity!='' && price !='' ) $('#total_'+id[1]).val( (parseFloat(price)*parseFloat(quantity)).toFixed(2) ); 
    calculateTotal();
});

$(document).on('change keyup blur','#tax',function(){
    calculateTotal();
});

//total price calculation 
function calculateTotal(){
    subTotal = 0 ; total = 0; 
    $('.totalLinePrice').each(function(){
        if($(this).val() != '' )subTotal += parseFloat( $(this).val() );
    });
    $('#subTotal').val( subTotal.toFixed(2) );
    tax = $('#tax').val();
    if(tax != '' && typeof(tax) != "undefined" ){
        taxAmount = subTotal * ( parseFloat(tax) /100 );
        $('#taxAmount').val(taxAmount.toFixed(2));
        total = subTotal + taxAmount;
    }else{
        $('#taxAmount').val(0);
        total = subTotal;
    }
    $('#totalAftertax').val( total.toFixed(2) );
    calculateAmountDue();
}

$(document).on('change keyup blur','#amountPaid',function(){
    calculateAmountDue();
});

//due amount calculation
function calculateAmountDue(){
    amountPaid = $('#amountPaid').val();
    total = $('#totalAftertax').val();
    if(amountPaid != '' && typeof(amountPaid) != "undefined" ){
        amountDue = parseFloat(total) - parseFloat( amountPaid );
        $('.amountDue').val( amountDue.toFixed(2) );
    }else{
        total = parseFloat(total).toFixed(2);
        $('.amountDue').val( total );
    }
}


//It restrict the non-numbers
var specialKeys = new Array();
specialKeys.push(8,46); //Backspace
function IsNumeric(e) {
    var keyCode = e.which ? e.which : e.keyCode;
    console.log( keyCode );
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
    return ret;
}

//datepicker
$(function () {
    $('#invoiceDate').datepicker({});
});

(ajax.php)

<?php

require_once 'config.php';
if(!empty($_POST['type'])){
    $type = $_POST['type'];
    $name = $_POST['name_startsWith'];
    $query = "SELECT model, category FROM products where UPPER($type) LIKE '".strtoupper($name)."%'";
    $result = mysqli_query($con, $query);
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['model'].'|'.$row['category'];>> 
        array_push($data, $name);
    }   
    echo json_encode($data);exit;
}

这是我想要发挥作用的一个例子。当您单击“Model#”字段时,它应该从具有所需数据的“products”数据库中自动更正。现在它有“模型,类别”,但最终结果应该是:

模型,类别,子类别,描述,成本,零售

我不能为我的生活弄清楚如何将其解决到自动填充正确的位置:(

1 个答案:

答案 0 :(得分:1)

在第一个代码中有两个必需的变量,名称类型,在数据库中进行查询以返回信息,正如我在第二个代码不是你在考虑..在创建查询之前..你也可以在浏览器上用dev工具检查控制台日志以获得错误

if(!empty($_POST['type'])){
    $type = $_POST['type'];
    $name = $_POST['name_startsWith'];
} else { return false; }

$query = "SELECT ID, model, category, subcategory, description, cost, retail FROM products where UPPER($type) LIKE '".strtoupper($name)."%'";
.... 

type var是输入类型元素中使用js的数据类型,并将其作为aditional post var发送..请点击此处:

html += '<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';

在这里

$(document).on('focus','.autocomplete_txt',function(){
    type = $(this).data('type');

在ajax调用中发送类型和名称变量

url : 'ajax.php',
    dataType: "json",
    method: 'post',
    data: {
       name_startsWith: request.term,
       type: type
    },

并且使用php $ _POST“捕获”这些变量你看到..在ajax调用数据选项make 2 vars name_startsWith,type 并在php代码中 $ type = $ _POST [ '类型']; $ name = $ _POST ['name_startsWith'];