簡體   English   中英

從javascript獲取變量並在php上為jQuery-Seat-Charts構建sql查詢

[英]Get variables from javascript and build a sql query on php for jQuery-Seat-Charts


我正在使用jQuery-Seat-Charts為我們的公司巴士構建一個簡單的預訂系統(如果我可以將其命名為系統)。 由於我不是javascript方面的專家,因此在確定如何完成此工作方面,我需要您的寶貴幫助。 我只想要從javascript中獲取變量,並在php上構建sql查詢,以將全部信息存儲在MySQL數據庫中。 我現在所擁有的是:

<div class="wrapper">
        <div class="container">
            <div id="seat-map">
                <div class="front-indicator">Front</div>

            </div>
            <div id="legend"></div>
            <div class="booking-details">
                <h2>Booking Details</h2>

                <h3> Selected Seats (<span id="counter">0</span>):</h3>
                <ul id="selected-seats"></ul>

                Total: <b><span id="total">0</span> &#8364;</b>

                <button class="checkout-button">Book&raquo;</button>

            </div>
            <div id="formulari">
                <ul id="formulari-ul"> </ul>
            </div>
        </div>
    </div>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="`jquery.seat-charts.js`"></script>

    <script>
        var firstSeatLabel = 1;

        $(document).ready(function() {
            var $cart = $('#selected-seats'),
                $formulari = $('#formulari-ul'),
                $counter = $('#counter'),
                $total = $('#total'),
                sc = $('#seat-map').seatCharts({
                map: [
                    '___f',
                    'ff',
                    'ee_e',
                    'ee_e',
                    'ee_e',
                    'eeee',
                ],
                seats: {
                    f: {
                        price   : 60,
                        classes : 'first-class', //your custom CSS class
                        category: 'First Class'
                    },
                    e: {
                        price   : 55,
                        classes : 'other-seats', //your custom CSS class
                        category: 'Other Seats'
                    }                   

                },
                naming : {
                    top : false,
                    getLabel : function (character, row, column) {
                        return firstSeatLabel++;
                    },
                },
                legend : {
                    node : $('#legend'),
                    items : [
                        [ 'f', 'available',   'First Class' ],
                        [ 'e', 'available',   'Other Seats'],
                        [ 'f', 'unavailable', 'Booked']
                    ]                   
                },
                click: function () {
                    if (this.status() == 'available') {
                        //let's create a new <li> which we'll add to the cart items
                        $('<li><strong>Seat #'+this.settings.label+' - Price: '+this.data().price+'&#8364; </strong> ('+this.data().category+') <a href="#" class="cancel-cart-item">[cancel]</a></li>')
                            .attr('id', 'cart-item-'+this.settings.id)
                            .data('seatId', this.settings.id)
                            .appendTo($cart);

                        $('<p><strong>[X] Seat #'+this.settings.label+':</strong> <input name="fullname" type="text" value="Full Name" /><input name="birthday" type="text" value="dd/mm/yyyy" size="10" /><input name="placeBirth type="text" value="Place" size="10" /><input name="nrPass" type="text" value="Nr Pass" size="10" /><input name="passFrom" type="text" value="dd/mm/yyyy" size="10" /><input name="passTo" type="text" value="dd/mm/yyyy" size="10" /></p>')
                            .attr('id', 'form-item-'+this.settings.id)
                            .data('seatId', this.settings.id)
                            .appendTo($formulari);

                        /*
                         * Lets update the counter and total
                         *
                         * .find function will not find the current seat, because it will change its stauts only after return
                         * 'selected'. This is why we have to add 1 to the length and the current seat price to the total.
                         */
                        $counter.text(sc.find('selected').length+1);
                        $total.text(recalculateTotal(sc)+this.data().price);

                        return 'selected';
                    } else if (this.status() == 'selected') {
                        //update the counter
                        $counter.text(sc.find('selected').length-1);
                        //and total
                        $total.text(recalculateTotal(sc)-this.data().price);

                        //remove the item from our cart
                        $('#cart-item-'+this.settings.id).remove();

                        //seat has been vacated
                        return 'available';
                    } else if (this.status() == 'unavailable') {
                        //seat has been already booked
                        return 'unavailable';
                    } else {
                        return this.style();
                    }
                }
            });

            //this will handle "[cancel]" link clicks
            $('#selected-seats').on('click', '.cancel-cart-item', function () {
                //let's just trigger Click event on the appropriate seat, so we don't have to repeat the logic here
                sc.get($(this).parents('li:first').data('seatId')).click();
            });

            //let's pretend some seats have already been booked
            sc.get(['1_4']).status('unavailable');

    });

    function recalculateTotal(sc) {
        var total = 0;

        //basically find every selected seat and sum its price
        sc.find('selected').each(function () {
            total += this.data().price;
        });

        return total;
    }

    </script>

如您所見,我具有單擊功能,當用戶單擊任何可用的座位時,將出現一個表格,該表格應由用戶填寫詳細信息。 我一直在進步,直到現在為止,現在我不知道如何獲取javascript變量,如座位號,座位價格和座位代碼(所有座位的編碼都類似於X_Y,其中X =該行,Y =該行的座位號); 並使用這些變量和表單中的信息構建一個sql查詢。
希望我能清楚地解釋自己的需求和問題,並希望有人能幫助我使我走上正確的路;-)
謝謝大家!
PS jquery.seat-chart.js文件可以在這里找到!

大家好
通過搜索許多天並測試了許多方法,我找到了這個解決方案。 可能會對其他曾經或將遇到與我相同的問題的人有所幫助。
如您所見,由於我決定將整個過程#formulari多個步驟,因此我刪除了所有的ID #formulari和div。 因此,我首先要做的(步驟1)是為每個選定的座位添加一些隱藏的輸入。 實際上使用POST創建了一個表單,將seatNR和seatCode傳遞到下一步; 並獲取有關客戶端的一些信息,例如姓名,電話號碼和電子郵件:

                <div class="wrapper">
                  <div class="col_12">
                <legend><strong>Details for person of contact</strong></legend>
            <div class="col_4">
                <label for="rezname"><strong>Your Name</strong> </label>
                <input id="rezEmri" name="rezEmri" type="text" class="col_12" value="" />
            </div>

            <div class="col_4">
                <label for="rezEmail"><strong>Your Email</strong> <span>where the reservation details will be sent</span></label>
                <input id="rezEmail" name="rezEmail" type="text" class="col_12" value="" />
            </div>

            <div class="col_4">
                <label for="rezTel"><strong>Your Phone Nr</strong> </label>
                <input id="rezTel" name="rezTel" type="text" class="col_12" value="" />
            </div>
        </div>
    <div class="container">
        <div id="seat-map">
            <div class="front-indicator">Front</div>

        </div>
        <div id="legend"></div>
        <div class="booking-details">
            <form action="transport.php?step=2" method="post">
            <h2>Booking Details</h2>

            <h3> Selected Seats (<span id="counter">0</span>):</h3>
            <ul id="selected-seats"></ul>

            Total: <b><span id="total">0</span> &#8364;</b>

            <button class="checkout-button">Next &raquo;</button>
            </form>

        </div>
    </div>
</div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="`jquery.seat-charts.js`"></script>

<script>
    var firstSeatLabel = 1;

    $(document).ready(function() {
        var $cart = $('#selected-seats'),
            $counter = $('#counter'),
            $total = $('#total'),
            sc = $('#seat-map').seatCharts({
            map: [
                '___f',
                'ff',
                'ee_e',
                'ee_e',
                'ee_e',
                'eeee',
            ],
            seats: {
                f: {
                    price   : 60,
                    classes : 'first-class', //your custom CSS class
                    category: 'First Class'
                },
                e: {
                    price   : 55,
                    classes : 'other-seats', //your custom CSS class
                    category: 'Other Seats'
                }                   

            },
            naming : {
                top : false,
                getLabel : function (character, row, column) {
                    return firstSeatLabel++;
                },
            },
            legend : {
                node : $('#legend'),
                items : [
                    [ 'f', 'available',   'First Class' ],
                    [ 'e', 'available',   'Other Seats'],
                    [ 'f', 'unavailable', 'Booked']
                ]                   
            },
            click: function () {
                    if (this.status() == 'available') {
                        <?php /*?>//let's create a new <li> which we'll add to the cart items<?php */?>
                        $('<li><strong>Seat #'+this.settings.label+' - Price: '+this.data().price+'&#8364; </strong> ('+this.data().category+') <a href="#" class="cancel-cart-item" style="color: #b71a4c;">[cancel]</a><input type="hidden" name="seatNR['+this.settings.label+']" value="'+this.settings.label+'"><input type="hidden" name="seatCode['+this.settings.label+']" value="'+this.settings.id+'"></li>')
                            .attr('id', 'cart-item-'+this.settings.id)
                            .data('seatId', this.settings.id)
                            .appendTo($cart);


                        .attr('id', 'form-item-'+this.settings.id)
                        .data('seatId', this.settings.id)
                        .appendTo($formulari);

                    /*
                     * Lets update the counter and total
                     *
                     * .find function will not find the current seat, because it will change its stauts only after return
                     * 'selected'. This is why we have to add 1 to the length and the current seat price to the total.
                     */
                    $counter.text(sc.find('selected').length+1);
                    $total.text(recalculateTotal(sc)+this.data().price);

                    return 'selected';
                } else if (this.status() == 'selected') {
                    //update the counter
                    $counter.text(sc.find('selected').length-1);
                    //and total
                    $total.text(recalculateTotal(sc)-this.data().price);

                    //remove the item from our cart
                    $('#cart-item-'+this.settings.id).remove();

                    //seat has been vacated
                    return 'available';
                } else if (this.status() == 'unavailable') {
                    //seat has been already booked
                    return 'unavailable';
                } else {
                    return this.style();
                }
            }
        });

        //this will handle "[cancel]" link clicks
        $('#selected-seats').on('click', '.cancel-cart-item', function () {
            //let's just trigger Click event on the appropriate seat, so we don't have to repeat the logic here
            sc.get($(this).parents('li:first').data('seatId')).click();
        });

        //let's pretend some seats have already been booked
        sc.get(['1_4']).status('unavailable');

});

function recalculateTotal(sc) {
    var total = 0;

    //basically find every selected seat and sum its price
    sc.find('selected').each(function () {
        total += this.data().price;
    });

    return total;
}

</script>

STEP 2 =>我從STEP 1的POST中獲取變量,並按以下方式處理信息:

if(isset($_GET['step']) && (mysql_real_escape_string(preg_replace('/[^0-9]/', '', $_GET['step']))=='2')) {
            $seatNR = $_POST['seatNR'];
            $seatCode = $_POST['seatCode'];
           // I'm not showing the client details process, as it's clear the way i do it :)

PS聯系人的詳細信息已在數據庫中注冊,並將與該特定預訂/預訂的旅行者詳細信息相關聯。 這樣,我們就會獲得預訂者的詳細信息,並將其與所有旅行者的詳細信息相關聯。

在我過濾輸入並進行所需的驗證(特定於將集成此選座器的系統上)之后,我將顯示輸入字段,訪客將在其中輸入旅客詳細信息(姓名,護照號碼等)。 這就是我做到的方式:

<?php
foreach( $seatNR as $key => $n ) {
  print '<tr>'; 
  print ' <td><strong style="font-size:14px;"><center>'.$n.'</center></strong></td>
  ';
  print '<td><input type="text" name="trav[][Name]" size="20" value=""></td>
  ';
  print '<td><input type="text" name="trav[][Birthday]" size="9" value=""></td>
  ';
  print '<td><input type="text" name="trav[][PlaceBirth]" size="14" value=""></td>
  ';
  print '<td><input type="text" name="trav[][passNr]" size="10" value=""></td>
  ';
  print '<input type="hidden" name="trav[][seatNR]" value="'.$n.'">
  ';
  print '<input type="hidden" name="trav[][seatCode]" value="'.$kodiVendit[$key].'">
  ';

  print '</tr>';
}
?>

因此,此foreach將與訪客選擇的座位一樣多地出現。 如果訪客選擇了5個座位,則會出現5行輸入字段。


STEP 3 =>將從STEP 2的表單中獲取全部信息,並在確認所有信息均符合預期后,將其插入MySQL數據庫中。
所以,這就是我所做的。 如果您有任何建議可以做得更好,我將非常高興知道。
祝大家好運;-)

編輯:我忘了為表單處理器添加循環。 如下:

// To get the last id of reservation and to insert it at traveler details.
// This way we create a connection btw the traveleres and who made the reservation
$sql33="SELECT rezID, rezDataRez FROM transport_reservations ORDER BY rezID DESC LIMIT 1;";
            $res33=mysql_query($sql33)or die(mysql_error().$sql33);
            $row33=mysql_fetch_array($res33);
            $$lastRezID=$row33[0];
// Start the verification and insertion of traveler details on the db
 define('HOST', '*********');
    define('DBNAME', '*********');
    define('USERNAME', '**********');
    define('PASSWORD', '********');
    $dbREZ = new mysqli(HOST,USERNAME,PASSWORD,DBNAME);

    $dataREZ = array();            
    foreach ($_POST['trav'] as $a) {
    /**
    * sanitize string data and format dates
    */  
    $dataREZ[] = sprintf("('%s','%s','%s','%s','%s','%s','%s')",
                $dbREZ->real_escape_string($lastRezID),
                $dbREZ->real_escape_string($a['Name']),
                date('Y-m-d', strtotime($a['Birthday'])),
                $dbREZ->real_escape_string($a['PlaceBirth']),
                $dbREZ->real_escape_string($a['passNr']),
                $dbREZ->real_escape_string($a['seatNr']),
                $dbREZ->real_escape_string($a['seatCode']),
                );

}
$sqlAddTrav = "INSERT INTO transport_travelers (rezID, travName, travBirthday, travBirthPlace, travPass, travSeatNr, travSeatCode) VALUES \n" . join(",\n", $dataREZ);
$dbREZ->query($sqlAddTrav);

希望這很清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM