Monday, January 22, 2018

How to Insert Form Data Using JavaScript/Jquery, PHP and MySQL ?

Javascript to get form data and post it to php through URL and
PHP to insert into table
Form : Form data will be stored in javascript varibles on submission by id (#FirstName,#LastName, #Email, #City). Post javascript varibles to the php through URL
<head> <link rel="stylesheet" href="CSS/Bootstrap.css"/> <script src=""></script> <script> function Add() { $(document).ready(function () { var FirstName = $("#FirstName").val(); var LastName = $("#LastName").val(); var Email = $("#Email").val(); var City = $("#City").val(); var variableString = 'FirstName=' + (FirstName) + '&LastName=' + (LastName) + '&Email=' + (Email) + '&City=' + (City); if ((FirstName == '') || (LastName == '') || (Email == '') || (City == '')) { alert("Please Fill All Fields"); } else { $.ajax({ type: "POST", url: "Add_User.php", data: variableString, cache: false, success: function (msg) { alert("Message: " + msg); } }); } }); } </script> </head> <body class="container"> <form method='post' class="form-horizontal"> <div class="col-md-12"> <div class="col-md-3"> <label>First Name</label> <input type="text" id="FirstName" class="form-control"> </div> <div class="col-md-3"> <label>Last Name</label> <input type="text" id="LastName" class="form-control"/> </div> </div> <div class="col-md-12"> <div class="col-md-3"> <label>Email</label> <input type="text" id="Email" class="form-control"/> </div> <div class="col-md-3"> <label>City</label> <input type="text" id="City" class="form-control"/> </div> </div> <div class="col-md-3"> <input type="submit" value="Submit" onclick="Add()"> </div> </form> </body> </html>
PHP Code to insert data submitted from the form.
//Connect to database
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";
$Connection = mysqli_connect
($DatabaseServer, $DatabaseUsername,
    $DatabasePassword, $DatabaseName);
if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
//Posted data
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Email = $_POST['Email'];
$City = $_POST['City'];
//Insert query
$SQL = mysqli_query($Connection,
    "INSERT INTO user (FirstName, LastName, Email, City)
 VALUES ('$FirstName', '$LastName', '$Email', '$City')");
CREATE TABLE `user` (   `UserID` int(12) NOT NULL,   `FirstName` varchar(48) NOT NULL,   `LastName` varchar(48) NOT NULL,   `Email` varchar(128) NOT NULL,   `City` varchar(48) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;