Form Submit with Ajax and Save to Php Mysql

Form Submit with Ajax and Save to Php Mysql


Hello to all, welcome to therichpost.com. In this post, I will tell you, Form Submit with Ajax and Save to Php Mysql.

I am sharing very simple, basic but very important html form submit with ajax and save to php mysql.

Here is the working example of saved data in mysql from ajax form post:


Form submit with ajax and save to php mysql

Here is the working and tested code and you need to add into your php and html files:

1. Very first, you need to add below code into you html file:
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <div class="container">
  <div class="jumbotron">
    <h2>Form submit with ajax and save to php mysql:</h2>
    <form action="/action_page.php">
      <div class="form-group">
      <label for="email">Email address:</label>
      <input type="femail" class="form-control" id="femail">
      <div class="form-group">
      <label for="name">Name:</label>
      <input type="fname" class="form-control" id="fname">
      <button type="submit" class="btn btn-primary">Submit</button>
      var email = $("#femail").val();
      var name = $("#fname").val();
      var dataString = 'email='+ email + '&name=' + name;
        data: dataString,
        success: function (data) {
2. Second, you need to add below code into your action_page.php file:

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "user";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

$sql = "INSERT INTO userdata (email, username)
VALUES ('".$email."', '".$name."')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;


Now this is done, If you have any query related to this post, then do comment below or ask questions.

Thank you,

Jatt Life,


Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Positive SSL