PHP jQuery Ajax Form Submit Example – Seat Booking

PHP Code Snippets No Comments

PHP jQuery Ajax Form Submit Example - Seat Booking

In this PHP jQuery Ajax Form Submit Example tutorial, we will be using a real-life example of Seat Booking of a bus, theatre, etc to understand how to process form data using Ajax without loading the page. This step-by-step tutorial will help you to develop a fully functional module for any movie ticket booking or flight ticket booking applications’ seat booking module. Let’s look at the different steps involved in this.

Step 1 – Add HTML:

Create an HTML file, say index.html, and use an <form> element to process the input. Then add inputs (with a matching label) for each field:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Seat Reservation with PHP & jQuery</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="ajax.js" type="text/javascript"></script>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>
    <form id="form1">
    
      <h2 style="font-size:1.2em;"> Choose seats by clicking the corresponding seat in the layout below:</h2>
       <div id="holder"> 
        <ul  id="place">
        </ul>    
       </div>
     <div style="width:600px;text-align:center;overflow:auto"> 
    	<ul id="seatDescription">
        <li style="background:url('images/available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
        <li style="background:url('images/booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
        <li style="background:url('images/selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
    	</ul>        
    </div>
    <div style="width:580px;text-align:left;margin:5px">	
        <input type="button" id="btnShowNew" value="Show Selected Seats" /><input type="button" id="btnShow" value="Show All" />            
    </div>
    <div id="sSeats"> </div>
    </form>
    
</body>
</html>
Step 2 – Add CSS:

To make our forms look better, will add the following code in the style.css file below:

#holder {
  height: 200px;
  width: 550px;
  background-color: #F5F5F5;
  border: 1px solid #A4A4A4;
  margin-left: 10px;
}

#place {
  position: relative;
  margin: 7px;
}

#place a {
  font-size: 0.6em;
}

#place li {
  list-style: none outside none;
  position: absolute;
}

#place li:hover {
  background-color: yellow;
}

#place .seat {
  background: url("images/available_seat_img.gif") no-repeat scroll 0 0 transparent;
  height: 33px;
  width: 33px;
  display: block;
}

#place .selectedSeat {
  background-image: url("images/booked_seat_img.gif");
}

#place .selectingSeat {
  background-image: url("images/selected_seat_img.gif");
}

#place .row-3,
#place .row-4 {
  margin-top: 10px;
}

#seatDescription {
  padding: 0px;
}

#seatDescription li {
  verticle-align: middle;
  list-style: none outside none;
  padding-left: 35px;
  height: 35px;
  float: left;
}
Step 3 – Ajax Processing:

Processing of Ajax will be done through the ajax.js file as shown below. This sends data to process.php file to process the data in the database.

$(function() {
    var settings = {
        rows: 5,
        cols: 15,
        rowCssPrefix: 'row-',
        colCssPrefix: 'col-',
        seatWidth: 35,
        seatHeight: 35,
        seatCss: 'seat',
        selectedSeatCss: 'selectedSeat',
        selectingSeatCss: 'selectingSeat'
    };

    var init = function(reservedSeat) {
        var str = [],
            seatNo, className;
        for (i = 0; i < settings.rows; i++) {
            for (j = 0; j < settings.cols; j++) {
                seatNo = (i + j * settings.rows + 1);
                className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
                if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
                    className += ' ' + settings.selectedSeatCss;
                }
                str.push('<li class="' + className + '"' +
                    'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
                    '<a title="' + seatNo + '">' + seatNo + '</a>' +
                    '</li>');
            }
        }
        $('#place').html(str.join(''));
    };

    //case I: Show from starting
    //init();

    //Case II: If already booked
    var bookedSeats = [5, 10, 25];
    init(bookedSeats);


    $('.' + settings.seatCss).click(function() {
        if ($(this).hasClass(settings.selectedSeatCss)) {
            alert('This seat is already reserved');
        } else {
            $(this).toggleClass(settings.selectingSeatCss);
        }
    });

    $('#btnShow').click(function() {
        var str = [];
        $.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
            str.push($(this).attr('title'));
        });
        alert(str.join(','));
    })

    $('#btnShowNew').click(function() {
        var str = [],
            item;
        $.each($('#place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
            item = $(this).attr('title');
            str.push(item);
        });
        $('#sSeats').html('<h3> Your selected seats are: ' + str.join(',') + '</h3>');
        // alert(str.join(','));
        $.ajax({
            type: 'POST',
            url: 'process.php',
            data: {
                selectedSeats: str.join(',')
            },
            success: function(e) {
                alert(e);
            }
        })

    })
});
Step 4 – Insert selected seat values in the database

Values of the selected seats will be inserted using the PHP file process.php as below:

<?php
include 'database_connection.php';
$connectdb = StartDatabaseConnection();
$seats = explode(',', $_POST['selectedSeats']);
$err = [];
foreach ($seats as $key => $value)
{
    $sql = 'INSERT INTO seats_booking (seat_no) VALUES ("' . $value . '")';
    if (!mysqli_query($connectdb, $sql))
    {
        $err = mysqli_error($connectdb);
    }
}

$arr = [];
if ($err === $arr)
{
    echo ('Successfully Inserted.');
}
else
{
    echo $err;
}
CloseDatabaseConnection($connectdb);
?>

Note: database_connection.php code is explained here in PHP Code for database connection.

Step 5 – Create the following table in the database for storing selected seat numbers:
DROP TABLE IF EXISTS `seats_booking`;
CREATE TABLE `seats_booking` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `seat_no` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Click the below link to check the demo. Download link to download the files used in this tutorial is also available on this page.
Demo

We used basic code from another website to complete this PHP jQuery Ajax Form Submit Example.
Credits

5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments