Как вставить динамические данные и статические входные данные в MySQL, используя ajax, динамические данные не будут вставлены - PullRequest
0 голосов
/ 04 октября 2019

У меня есть модальная форма со статическими полями ввода и динамическими полями ввода.

в настоящее время данные отправляются в базу данных mysql, статические поля вставляются в базу данных, но динамические поля невставлен.

Данные формы должны быть вставлены в три таблицы MySQL. Таблицы заказов, продуктов и сма.

HTML-код ввода

<div class="modal fade" tabindex="-1" role="dialog" id="insertModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
    <form class="well form-horizontal" action="" method="post" id="">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h3 class="modal-title">Insert Order Details</h3>
                </div><hr>
        <fieldset>

            <!-- Text input-->

            <div class="form-group">
                <label for="customer" class="col-md-4 control-label">Customer Name</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                        <input name="customer" id="customer" placeholder="Customer" class="form-control" type="text">
                        <label id="lblcustomer" style="color:red"></label>
                    </div>
                </div>
            </div>

            <!-- Text input-->

            <div class="form-group">
                <label for="date" class="col-md-4 control-label">Date</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                        <input name="date" id="date" placeholder="Date" class="form-control" type="date">
                        <label id="lbldate" style="color:red"></label>
                    </div>
                </div>
            </div>

            <!-- Text input-->
            <div class="form-group">
                <label for="invoice" class="col-md-4 control-label">Invoice</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                        <input name="invoice" id="invoice" placeholder="Invoice" class="form-control" type="text">
                        <label id="lblinvoice" style="color:red"></label>
                    </div>
                </div>
            </div>

            <!-- Text input-->
            <div class="form-group" id="container">
                <label for="product" class="col-md-4 control-label">Product Description</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                        <textarea name="product[]" id="product" class="form-control" placeholder="Product Description"></textarea>
                        <label id="lblproduct" style="color:red"></label>
                    </div>
                    <a href="#" id="add" style="text-align:center;">Add More</a>
                </div>
            </div>

            <!-- Text input-->

            <div class="form-group" id="container1">
                <label for="sma_number" class="col-md-4 control-label">SMA Number</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-barcode"></i></span>
                        <input name="sma_number[]" id="sma_number" placeholder="SMA Number" class="form-control" type="text">
                        <label id="lblsma_number" style="color:red"></label>
                    </div>
                    <a href="#" id="add1" style="text-align:center;">Add More</a>
                </div>
            </div>

            <!-- Text input-->

            <div class="form-group">
                <label for="ebay" class="col-md-4 control-label">eBay Item Number</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-qrcode"></i></span>
                        <input name="ebay" id="ebay" placeholder="eBay Number" class="form-control" type="text">
                        <label id="lblebay" style="color:red"></label>
                    </div>
                </div>
            </div>

            <!-- Text input-->

            <div class="form-group">
                <label for="shipper" class="col-md-4 control-label">Shipped With</label>
                <div class="col-md-7 selectContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-road"></i></span>
                        <select name="shipper" id="shipper" class="form-control selectpicker">
                            <option value=" ">Please select Shipping Company</option>
                            <option>DHL</option>
                            <option>TNT</option>
                            <option>FEDEX</option>
                            <option>AUSPOST</option>
                            <option>PickUp</option>
                        </select>
                        <label id="lblshipper" style="color:red"></label>
                    </div>
                </div>
            </div>

            <!-- Text input-->

            <div class="form-group">
                <label for="tracking" class="col-md-4 control-label">Tracking Number</label>
                <div class="col-md-7 inputGroupContainer">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
                        <input name="tracking" id="tracking" placeholder="Tracking No" class="form-control" type="text">
                        <label id="lbltracking" style="color:red"></label>
                    </div>
                </div>
            </div>
        </fieldset>
                <!-- Button -->
                 <div class="modal-footer">
                    <input type="button" name="save" id="save" value="Save Order" class="btn btn-success">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
    </form>

Ajax-скрипт

<script>

        $(document).ready(function(e){
        //Variables
        var html = '<div class="form-group"><label class="col-md-4 control-label">Product</label><div class="col-md-6 inputGroupContainer1" style="padding-left: 20px"><input name="product[]" id="product[]" placeholder="Product" class="form-control" type="text"></div><button id="remove" class="btn btn-danger i_remove_me pull-left" >-</button></div';
        var maxRows = 5;
        var x = 1;

        //Add Rows to the form
        $("#add").click(function(e){ 
            e.preventDefault();
            if(x <= maxRows){
            $("#container").append(html);
            x++;
            }
        });

        //Remove rows from the from
        $("#container").on('click','#remove', function(e){
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        });

    });

        $(document).ready(function(e){
        //Variables
        var html1 = '<div class="form-group"><label class="col-md-4 control-label">SMA</label><div class="col-md-4 inputGroupContainer1" style="padding-left: 20px"><input name="sma_number[]" id="sma_number[]" placeholder="SMA Number" class="form-control" type="text"></div><button id="remove" class="btn btn-danger i_remove_me pull-left" >-</button></div';
        var maxRows = 5;
        var x = 1;

        //Add Rows to the form
        $("#add1").click(function(e){ 
            e.preventDefault();
            if(x <= maxRows){
            $("#container1").append(html1);
            x++;
            }
        });

        //Remove rows from the from
        $("#container1").on('click','#remove', function(e){
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        });

    });

</script>
<script>
    //datatable
    $(document).ready(function() {
        $("#emp_table_details").DataTable();
    });


    $(document).ready(function() {
        //Save Or Insert Data
        $(document).on('click', '#save', function() {
            var customer = $("#customer").val();
            var date = $("#date").val();
            var invoice = $("#invoice").val();
            var product = $("#product").val();
            var sma_number = $("#sma_number").val();
            var ebay = $("#ebay").val();
            var shipper = $("#shipper").val();
            var tracking = $("#tracking").val();
            if (customer == "") {
                $("#lblcustomer").html("Customer Name Required!");
            } else if (date == "") {
                $("#lbldate").html("Date Required!");
            } else if (invoice == "") {
                $("#lblinvoice").html("Invoice Number Required!");
            } else if (product == "") {
                $("#lblproduct").html("Product Required!");
            } else if (sma_number == "") {
                $("#lblsma_number").html("SMA Number Required!");
            } else if (ebay == "") {
                $("#lblebay").html("eBay Number Required!");
            } else if (shipper == "") {
                $("#lblshipper").html("Shipper Required!");
            } else if (tracking == "") {
                $("#lbltracking").html("Tracking Required!");
            } else {
                $.ajax({
                    url: "ajaxsave.php",
                    type: "post",
                    data: {
                        customer: customer,
                        date: date,
                        invoice: invoice,
                        product: product,
                        sma_number: sma_number,
                        ebay: ebay,
                        shipper: shipper,
                        tracking: tracking
                    },
                    success: function() {
                        alert('Your Data Save Sucessful');
                        //document.getElementById('insert_form').reset();
                        //$("#emp_table_details").load('select_data.php');
                        $("#insertModal").modal('hide');
                        location.reload();
                    }
                });
            }
        });
</script>

вставка PHP в код MYSQL

<?php include 'config/config.php'; ?>
<?php
global $con;
//if (isset($_POST)) {

    $customer = $_POST['customer'];
    $date = $_POST['date'];
    $invoice = $_POST['invoice'];
    $product = $_POST['product'];
    $sma_number = $_POST['sma_number'];
    $ebay = $_POST['ebay'];
    $shipper = $_POST['shipper'];
    $tracking = $_POST['tracking'];;

    $sql = "INSERT INTO orders(customer, date, invoice, ebay, shipper, tracking)
          VALUES('$customer','$date','$invoice','$ebay','$shipper','$tracking')";

    $query = mysqli_query($con, $sql);

    $newOrderId = mysqli_insert_id($con);

    if($query){
    $sql1 = "INSERT INTO products(id, product) VALUES('$newOrderId','$product')";
    $sql2 = "INSERT INTO sma(id, sma_number) VALUES('$newOrderId','$sma_number')";

    $result = mysqli_query($con,$sql1);
    $result2 = mysqli_query($con,$sql2);

    }
?>

1 Ответ

0 голосов
/ 04 октября 2019

Адаптируйте вызов AJAX следующим образом:

var form = $("#submissionForm")[0]; //remember to give your form name the id submissionForm
var formData = new FormData(form);              

 $.ajax({
    url: "ajaxsave.php",
    type: "post",
    data: formData,
    contentType: false,
    cache: false,
    processData: false,
    async: true,
    success: function() {
        alert('Your Data Save Sucessful');
        //document.getElementById('insert_form').reset();
        //$("#emp_table_details").load('select_data.php');
        $("#insertModal").modal('hide');
        location.reload();
    }
}); 

Затем вы можете проверить, какие значения получает ваш PHP-файл, записав их в файл следующим образом:

<?php
$output = "POSTed variables:\n";    

$customer = $_POST['customer']; $output .= "customer = $customer\n";    
$date = $_POST['date']; $output .= "date = $date\n";
$invoice = $_POST['invoice']; $output .= "invoice = $invoice\n";    

$products = $_POST['product'];  
if (is_array($products))
{ 
  for ($i=0; $i<sizeof($products); $i++)
  {
    $products[$i]; //the value of the array at index i. Save each of these to the database
    $output .= "product[".$i."] = $products[$i]\n";
  }
}    

$sma_number = $_POST['sma_number'];
if (is_array($sma_number))
{ 
  for ($i=0; $i<sizeof($sma_number); $i++)
  {
    $sma_number[$i]; //the value of the array at index i. Save each of these to the database
    $output .= "sma_number[".$i."] = $sma_number[$i]\n";
  }
}

$ebay = $_POST['ebay']; $output .= "ebay = $ebay\n";
$shipper = $_POST['shipper']; $output .= "shipper = $shipper\n";
$tracking = $_POST['tracking']; $output .= "tracking = $tracking\n";

file_put_contents( 'POSTed_vars.txt', $output ); // DEBUG

?>

Я проверил кодзаполнив вашу модальную форму несколькими продуктами и несколькими номерами sma. Текстовый файл POSTed_vars.txt содержал следующее, и это именно то, что я вставил в форму. Теперь ваша задача - записать эти значения в базу данных.

POSTed variables:
customer = John Doe
date = 2019-10-05
invoice = inv12345
product[0] = Blue Teddy Bear
product[1] = Green Teddy Bear
product[2] = Red Teddy Bear
sma_number[0] = sma12345
sma_number[1] = sma67891
ebay = ebay12345
shipper = DHL
tracking = track12345

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...