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
Add_User.html
<html>
<head> <link rel="stylesheet" href="CSS/Bootstrap.css"/> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></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>
Add_User.php
PHP Code to insert data submitted from the form.
<?php
//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')");
?>
HTML Form
MySQL
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;

No comments:

Post a Comment

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts