jQuery Ajax is the powefull tool of jQuery, You can create attractive webpage with the help of JQuery ajax. jQuery's Ajax methods return a superset of the XMLHTTPResuest object.
There are two commonly used methods for a request between a client and server: GET and POST.
GET - Requests data from a specified resource, basically used for just retrieving some data from the server.
POST - Submits data to be processed to a specified resource, used for setting some data to the server and also can retrieving tha data. POST method never caches data.
Ajax request is just like a web page call. Only difference is that the user doesn’t have to reload the page and user operation will be performed. Before you call a Ajax request you need to set JQuery link in your page, You can also download it.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
Let’s get start with a basic JQuery Ajax POST request:
$.ajax({
type: "POST",
url: 'server.php',
success: function(data){
alert(data);
},
error: function (Status, errorThrown) {
}
});
Now create a Ajax page on your project where you can place your MySQL code with php script. You can set your file name like server_ajax.php
<?php
require_once('config.php');
if(isset($_POST['firstname']) && isset($_POST['lastname']) && && isset($_POST['email']) ){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$sql = "INSERT INTO my_ajax (firstname, lastname, email)
VALUES ($firstname, $lastname, $email)";
if (mysqli_query($conn, $sql)) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
else{
echo "Something went wrong";
}
mysqli_close($conn);
?>
Finally create your index page to call server_ajax.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery Ajax POST Example</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: 'server_ajax.php',
data: {firstname: 'Tony', lastname: 'stark', email: 'tony@mymail.com'},
success: function(data){
$("#result").append(data);
}
});
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>