Submit Form using AJAX in PHP/MySQLi

Status
Not open for further replies.

lazenes

Banned
Banned
Member
Joined
Threads
132
Posts
414
This member is banned. Please avoid dealing with banned members.
screeshot.png

This tutorial will teach you on how to submit form and retrieve the values of the form in the url of your AJAX code. The primary code of this tutorial is serialize() function which will convert our form to be ready to process into our AJAX.

Note: Scripts and css used in this tutorial are hosted, therefore, you need internet connection for them to work.

Creating our Database
First step is to create our database.
1. Open phpMyAdmin.
2. Click databases, create a database and name it as sample.
3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
Code:
CREATE TABLE `user` (
  `userid` INT(11) NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(30) NOT NULL,
  `lastname` VARCHAR(30) NOT NULL,
  `username` VARCHAR(30) NOT NULL,
  `password` VARCHAR(30) NOT NULL,
  `address` VARCHAR(100) NOT NULL,
PRIMARY KEY(`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
database_6_16.png


Creating our Connection
Next, we create our connection to our database. This will serve as the bridge between our forms and database. We name this as conn.php.

PHP:
<?php

$conn = mysqli_connect("localhost","root","","sample");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

?>
index.php




We show our form in this page together with our sample user table to show that our form has been submitted via AJAX.
Code:
<!DOCTYPE html>
<html>
<head>
    <title>Submit Form using AJAX in PHP/MySQLi</title>
    <script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
" rel="nofollow">https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></scri...</a>    <link rel="stylesheet" href="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"</a> />
    <script src="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></s...</a>    <style>
        .title{
            font-size:30px;
            color:blue;
        }
        .main{
            width:60%;
            padding:auto;
            margin:auto;
        }
        .h20{
            height:20px;
        }
        .h10{
            height:10px;
        }
        .desc{
            position:relative;
            top:6px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="h20"></div>
    <div class="well main">
        <div class="row">
            <div class="col-lg-12">
                <span class="title"><center>Submit Form using AJAX in PHP/MySQLi</center></span>
            </div>
        </div>
        <div class="h20"></div>
        <form id="form">
        <div class="row">
            <div class="col-lg-2">
                <span class="desc">Firstname:</span>
            </div>
            <div class="col-lg-10">
                <input type="text" name="firstname" class="form-control">
            </div>
        </div>
        <div class="h10"></div>
        <div class="row">
            <div class="col-lg-2">
                <span class="desc">Lastname:</span>
            </div>
            <div class="col-lg-10">
                <input type="text" name="lastname" class="form-control">
            </div>
        </div>
        <div class="h10"></div>
        <div class="row">
            <div class="col-lg-2">
                <span class="desc">Username:</span>
            </div>
            <div class="col-lg-10">
                <input type="text" name="username" class="form-control">
            </div>
        </div>
        <div class="h10"></div>
        <div class="row">
            <div class="col-lg-2">
                <span class="desc">Password:</span>
            </div>
            <div class="col-lg-10">
                <input type="password" name="password" class="form-control">
            </div>
        </div>
        <div class="h10"></div>
        <div class="row">
            <div class="col-lg-2">
                <span class="desc">Address:</span>
            </div>
            <div class="col-lg-10">
                <input type="text" name="address" class="form-control">
            </div>
        </div>
        </form>
        <div class="h10"></div>
        <div class="row">
            <div class="col-lg-12">
                <button type="button" class="btn btn-primary pull-right" id="submit">Submit</button>
            </div>
        </div>
    </div>
    <div class="h20"></div>
    <div class="row">
        <div id="table">
        </div>
    </div>
</div>
<script src="custom.js"></script>
</body>
</html>
custom.js
This script contains our fetch user and add user code. Also, you will see in this script how we serialize our form to be submitted.

Code:
$(document).ready(function(){

    showTable();

    $('#submit').click(function(){
        var form=$('#form').serialize();
        $.ajax({
            url:"add.php",
            method:"POST",
            data:form,
            success:function(){
                showTable();
                $('#form')[0].reset();
            }
        });
    });
});

function showTable(){
    $.ajax({
        url:"fetch.php",
        method:"POST",
        data:{
            fetch: 1,
        },
        success:function(data){
            $('#table').html(data);
        }
    });
}
fetch.php
This is our PHP code in fetching user from our database to show in our table.
Code:
<?php
    include('conn.php');
    if(isset($_POST['fetch'])){
        ?>
        <table class="table table-bordered table-striped">
            <thead>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Username</th>
                <th>Password</th>
                <th>Address</th>
            </thead>
            <tbody>
                <?php
                    $query=mysqli_query($conn,"select * from user order by userid desc");
                    while($row=mysqli_fetch_array($query)){
                    ?>
                    <tr>
                        <td><?php echo $row['firstname']; ?></td>
                        <td><?php echo $row['lastname']; ?></td>
                        <td><?php echo $row['username']; ?></td>
                        <td><?php echo $row['password']; ?></td>
                        <td><?php echo $row['address']; ?></td>
                    </tr>
                    <?php
                    }
                ?>
            </tbody>
        </table>
        <?php  
    }
?>
add.php
Lastly, our code in adding new row to our database from the form that we serialize and submitted via AJAX.


You must reply to see the hidden content. Consider upgrading your account to increase your reply limit.
That ends this tutorial. If you have any comments or questions, feel free to write it below or message me and I will answer it to the best of my ability. Happy Coding :)
 
@lazenes Good tutorial, but better to use PDO
 
wont let me quote you but here you go

heres some pictures of what i did








im sure you can see how the register works (same as login)

download link
You must reply to see the hidden content. Consider upgrading your account to increase your reply limit.


so heres what i did
  • re wrote it all in pdo
  • hashed passwords with bcrypt
  • still runs using ajax requests
  • sanitized all inputs etc
im sure you can see for yourself/ i dont take any credit, apart from what i did to it :p
 
Status
Not open for further replies.