Insert Data in PHP using JQuery AJAX without page Refresh

Insert Data in PHP using JQuery AJAX without page Refresh

Jquery ajax and php is best combination for  sending post or get request to any server in less execution time. jquery ajax get request simple and faster then post request and no limitation for sending data using post request post request secure and mostly used.

It is possible to send request to server without page load using ajax request.

//Jquery Ajax Get/Post Request
$.ajax(
{
url: "Url",
type: GET/POST
success: function(result){
}
});
//Jquery simple Post Request
$.post('your url',
{
//required parameter
}, function(data){
//response decision
});
//Jquery get Request
$.post('your url',
{
//required parameter
}, function(data){
//response decision
})
Insert Data Without Page Load
1.index.php (Registration Page)

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Registration Form</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
    <div class="row" style="padding-top: 40px;">

    <div class="col-md-3">

    </div>
    <div class="col-md-6 bg-primary" style="padding-top: 30px; padding-bottom: 30px;">
        <h2>Data Insertion Without Page Load</h2>
        <div class="alert alert-success">
            <strong>Success!</strong> data inserted successfully.
        </div>
        <div class="alert alert-danger">
            <strong>Failed!</strong> Data insertion problem.
        </div>
        <form method="post" id="reg_form">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" id="name" placeholder="Enter name" name="name" required="">
            </div>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" required="">
            </div>
            <div class="form-group">
                <label for="sal">Salary:</label>
                <input type="number" min="1000" class="form-control" id="sal"  name="sal" required="">
            </div>

            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
    <div class="col-md-3">

    </div>

</div>

</div>
<script>
    $(document).ready(function(){
        $(".alert-success").hide();
        $(".alert-danger").hide();
//        alert(100);
        $("#reg_form").submit(function(e){
            e.preventDefault();
//            alert(120);
            var name =$("#name").val();
            var email =$("#email").val();
            var salary =$("#sal").val();
            $.post("registration.php",
                {
                    name: name,
                    email: email,
                    salary: salary
                },
                function(data){
                    data= $.trim(data);
                    if(data=="Success")
                    {
                        $(".alert-success").show();

                        $("#name").val('');
                        $("#email").val('');
                        $("#sal").val('');
                    }
                    else{
                        $(".alert-danger").show();
                    }

                });
        })
    })
</script>


</body>
</html>

2.connection.php(database Connection pdo driver)
<?php
class DatabaseConnection
{


    private $host ='localhost';
    private $dbname = 'reg_record';
    private $username = 'root';
    private $password = '';


//my_password
    public $con = null;

    function __construct(){

        $this->connect();
    }

    function connect(){

        try{

            $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

            $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            //echo "yes";

        }catch(PDOException $e){


            echo 'We\'re sorry but there was an error while trying to connect to the database'.$e->getMessage();
            file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);

        }
    }
}

//$dbcon=new DatabaseConnection();
//$dbcon->connect();
?>

3. Registration.php (backend php page)
<?php
require("connection.php");
$db=new DatabaseConnection();
if($_POST['name'])
{
    $name=$_POST['name'];
    $email=$_POST['email'];
    $salary=$_POST['salary'];
    $query=$db->con->prepare("insert into registration(`name`,`email`,`salary`)VALUE('$name','$email','$salary')");
    $query->execute();
    $row =$query->rowCount();
    if($row>0){
        echo"Success";
    }else{
        echo"failed";
    }

}else{
    echo"failed";
}


?>

Response of the the code:-

 

 

 

One Reply to “Insert Data in PHP using JQuery AJAX without page Refresh”

  1. Hi admin, i must say you have high quality posts here.
    Your website can go viral. You need initial traffic
    boost only. How to get it? Search for: make your content go viral Wrastain’s tools

Leave a Reply

Your email address will not be published. Required fields are marked *