[Javascript] prenotazione posti a teatro jQuery-Seat-Charts

giumazzi

Nuovo Utente
16 Feb 2017
27
2
3
provincia PESARO
Ho un progetto php che prenota dei posti a teatro utilizzando una personalizzazione di questo plugin JQuery
https://github.com/mateuszmarkowski/jQuery-Seat-Charts
Questi sono i codici dei file utilizzati nel progetto.
booking.js presonalizzazione di jQuery-Seat-Charts
Codice:
var price = 10; //prezzo
var $cart = $('#selected-seats'); //Area dei posti
var $counter = $('#counter'); //prenotazioni
var $total = $('#total'); //costo totale

var sc = $('#seat-map').seatCharts({
    map: [  //Seating chart
  'aaaaaaaaaa',
  'aaaaaaaaaa',
  'aaaaaaaaaa',
  'aaaaaaaaaa',
  'aaaaaaaaaa'
    ],
    naming : {
      top : false,
      getLabel : function (character, row, column) {
          return column;
      }
    },
    legend : { //Definition legend
       node : $('#legend'),
       items : [
         [ 'a', 'available',   'Disponibile' ],
         [ 'a', 'unavailable', 'prenotato']
        ]
    },
    click: function () { //Click event
       if (this.status() == 'available') { //posti disponibili
          var maxSeats = 3;
          var ms = sc.find('selected').length;
          //alert(ms);
           if (ms < maxSeats) {
              $('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+'</option>')
                  .attr('id', 'cart-item-'+this.settings.id)
                  .attr('value', (this.settings.row+1)+'_'+this.settings.label)
                  .data('seatId', this.settings.id)
                  .appendTo($cart);

              $counter.text(sc.find('selected').length+1);
              $counter.attr('value', sc.find('selected').length+1);

              $total.text(recalculateTotal(sc)+price);
              $total.attr('value', recalculateTotal(sc)+price);

               return 'selected';
           }
             alert('You can only choose '+ maxSeats + ' seats.');
             return 'available';

        } else if (this.status() == 'selected') { //Selezionato Checked

          //Update Number
             $counter.text(sc.find('selected').length-1);
             $counter.attr('value', sc.find('selected').length-1);
          //update totalnum
             $total.text(recalculateTotal(sc)-price);
             $total.attr('value', recalculateTotal(sc)-price);

          //Delete reservation
            $('#cart-item-'+this.settings.id).remove();
          //optional
            return 'available';

        } else if (this.status() == 'unavailable') { //Prenotato sold
          return 'unavailable';

        } else {
          return this.style();
        }
    }
});

// Add total money
function recalculateTotal(sc) {
    var total = 0;
    sc.find('selected').each(function () {
      total += price;
    });

  return total;
}
book.php pagina dei form che legge booking.js
PHP:
<?php
session_start();
include 'connection.php';
include 'functions/booking.php';
?>
. . .
            <div class="col-md-5">
              <div class="booking-details">
              <form role="form" id="myfrm1" action="book.php?id=<?php echo $FILM_ID; ?>" method="post">
                  <p>
                      <p>Date: <input type="date" class="form-control" id="date" name="date" value="2016-01-11" min="2016-01-11" max="2016-01-20" onchange="myfunctionDate(this.value)"></p>
                  </p>
                  <p>
                    <p for="session">Time:</p>
                    <select class="form-control" id="session" name="session" onchange="myfunctionTime(this.value)">
                      <option selected="selected" value="12:00">12:00</option>
                      <option value="16:00">16:00</option>
                      <option value="20:00">20:00</option>
                      </select>
                  </p>
                  <button type="submit" style="display: block; width: 100%;" name="change" value="change" class="btn btn-info">Cambia data</button>
              </form>

                <?php if (isset($_POST['change'])) {?>
                <?php
                // Film session
                $session = isset($_POST['session']) ? $_POST['session'] : '12:00';

                // Film date
                $date = isset($_POST['date']) ? $_POST['date'] : '2016-01-11';

                $query = "SELECT * FROM booking WHERE (FILM_ID = '$film_id' AND BOOKING_SESSION = '$session' AND BOOKING_DATE = '$date')";
                $result = mysqli_query ($connection,$query) or die ("<div class='alert alert-danger' role='alert'>Non puoi eseguire la query</div>");
                ?>

              <div class="demo" style="margin-top:10px;min-width: 360px;">
                  <div id="seat-map">
                      <div class="front">SCREEN</div>       
                 </div>
                   <div id="legend"></div>
                </div>

               <form role="form" id="myfrm2" action="book.php?id=<?php echo $FILM_ID; ?>" method="post">
                  <input type="hidden" name="session" value="<?php echo $session; ?>">
                  <input type="hidden" name="date" value="<?php echo $date; ?>">
                  <select class="form-control" style="display:block;" id="selected-seats" name="seat[]" multiple="multiple"></select>
                  <p>Tickets: <input id="counter" name="counter" readonly></input></p>
                  <p>Total: <b>&pound;<input id="total" name="total" readonly></input></b></p>
                  <button type="submit" style="display: block; width: 100%;" name="book" value="book" class="btn btn-danger">Book</button>
               </form>
             <?php } ?>       
              </div>
                <div style="clear:both;padding-top: 70px;"></div>
            </div>
. . .
.
    <!-- jQuery -->
    <script src="js/jquery.js"></script>
    
    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>
    <!-- Booking JavaScript -->
    <script type="text/javascript" src="js/seat-charts.min.js"></script>
    <script type="text/javascript" src="js/booking.js"></script>
    <script type="text/javascript">
    <?php
    //Fetch all rows for each booking   
    echo " $(document).ready(function(){";
    while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)) {
      extract ($row);
      echo "sc.get(['".$BOOKING_SEAT."']).status('unavailable'); \n";
    }
    echo "});";
    ?>
    </script>
booking.php file che inserisce i dati nel db
PHP:
<?php
if (isset($_POST['book'])) {
    $date = $_POST["date"];
    $session = $_POST["session"];
    $counter = $_POST["counter"];
    $total = $_POST["total"];
    $user_id = $_SESSION["id"];
    $film_id = $_GET['id'];
    $seat = (isset($_POST['seat']) ? $_POST['seat']:array());
    if (is_array($seat)) {                   
        foreach ($seat as $selectedOption){
           $query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, BOOKING_PRICE, BOOKING_NUM)
              VALUES ('$user_id','$film_id','$session','$date','$selectedOption','$total','$counter')";

            $result = mysqli_query ($connection,$query)
                or die ("<div class='alert alert-danger' role='alert'>Non Puoi eseguire la query</div>");   
            }
        echo "    <div class='alert alert-success' role='success'>
              Grazie per la tua prenotazione! Stampa la prenotazione <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
                </div>";
    }
   
}
?>
In questa configurazione il progetto funziona; i dati vengono inseriti nel db, la mappa con le prenotazioni aggiornata ecc....
Ma, il file booking.js è una personalizzazione di jQuery Seat-Chart (plugin che consente l'inserimento di diverse opzioni)
Da non esperto di JQuery ho provato a metterci le mani per cambiare il file booking.js con lo script originale (vedi html del file d'esempio qui sotto):
http://jsc.mm-lamp.com/

Le principali differenze risiedono:
1)nel prezzo (price) che nel file booking.js è dato come variabile mentre nell’originale è contenuto all’interno di seats
Codice:
seats: {
                           f: {
                                  price   : 100,
                                  classes : 'first-class', //your custom CSS class
                                  category: 'First Class'
                                 },
2) e nella funzione click
Codice:
                   click: function () {
                             if (this.status() == 'available') {
                                    //let's create a new <li> which we'll add to the cart items
                                    $('<li>'+this.data().category+' Seat # '+this.settings.label+': <b>$'+this.data().price+'</b> <a href="#" class="cancel-cart-item">[cancel]</a></li>')
                                     .attr('id', 'cart-item-'+this.settings.id)
                                     .data('seatId', this.settings.id)
                                           .appendTo($cart);

                                               $counter.text(sc.find('selected').length+1);
                                               $total.text(recalculateTotal(sc)+this.data().price);

                                               return 'selected';
Ho provato a fare delle modifiche per adattare booking.j a JQuery-Seat-Chart, riesco solo a visualizzare la mappa, ma non riesco ad inserire i dati ( il problema dovrebbe risiedere qui)
Codice:
$('<li>'+this.data().category+' Seat # '+this.settings.label+': <b>$'+this.data().price+'</b> <a href="#" class="cancel-cart-item">[cancel]</a></li>')
Chiedo agli esperti di JQuery un aiuto.
 

giumazzi

Nuovo Utente
16 Feb 2017
27
2
3
provincia PESARO
Trovato la soluzione modificando il file booking.js così
Codice:
var price = 0; //price
var $cart = $('#selected-seats'); //Sitting Area
var $counter = $('#counter'); //Votes
var $total = $('#total'); //Total money

var sc = $('#seat-map').seatCharts({
    map: [  //Seating chart
        'aaaaaaaaaa',
    'aaaaaaa__a',
    'aaaaaaaaaa',
    'aaaaaaaaaa',
        'aaaaaaabbb'
    ],
    naming : {
        top : true,
        rows: ['A','B','C','D','E'],
        getLabel : function (character, row, column) {
            return column;
        }
    },
    seats:{
        a:{
            price: 99.9
        },
        b:{
            price: 200
        }
    },
    legend : { //Definition legend
        node : $('#legend'),
        items : [
            [ 'a', 'available',   'Option' ],
            [ 'a', 'unavailable', 'Sold']
        ]
    },
    click: function () { //Click event
        if (this.status() == 'available') { //optional seat
            var maxSeats = 3;
            var ms = sc.find('selected').length;
            //alert(ms);
            if (ms < maxSeats) {
                
                price = this.settings.data.price;
                
                /*
                    $('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+'</option>')
                    .attr('id', 'cart-item-'+this.settings.id)
                    .attr('value', (this.settings.row+1)+'_'+this.settings.label)
                    .data('seatId', this.settings.id)
                    .appendTo($cart);
                */
                    
                    $('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+'</option>')
                    .attr('id', 'cart-item-'+this.settings.id)
                    .attr('value', this.settings.id)
                    .attr('alt', price)
                    .data('seatId', this.settings.id)
                    .appendTo($cart);

                $counter.text(sc.find('selected').length+1);
                $counter.attr('value', sc.find('selected').length+1);

                $total.text(recalculateTotal(sc));
                $total.attr('value', recalculateTotal(sc));

                return 'selected';
            }
                alert('You can only choose '+ maxSeats + ' seats.');
                return 'available';

        } else if (this.status() == 'selected') { //Checked

                //Update Number
                $counter.text(sc.find('selected').length-1);
                $counter.attr('value', sc.find('selected').length-1);
                //update totalnum
                $total.text(recalculateTotal(sc));
                $total.attr('value', recalculateTotal(sc));

                //Delete reservation
                $('#cart-item-'+this.settings.id).remove();
                //optional
                return 'available';

        } else if (this.status() == 'unavailable') { //sold
            return 'unavailable';

        } else {
            return this.style();
        }
    }
});
function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-line camelcase
 
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  var s = ''
  var toFixedFix = function (n, prec) {
    var k = Math.pow(10, prec)
    return '' + (Math.round(n * k) / k)
      .toFixed(prec)
  }
  // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

// Add total money
function recalculateTotal(sc) {
    var total = 0;
    $('#selected-seats').find('option:selected').each(function () {
        total += Number($(this).attr('alt'));
    });

    return number_format(total,2,'.','');
}