get()
and post()
methods are used to request data from the server with an HTTP GET or POST methods .get()
method is requests data from a specified resourcepost()
method is submits data to be processed to a specified resource$.get()
makes Ajax requests using the HTTP GET method, whereas the $.post()
makes Ajax requests using the HTTP POST method.$.get()
method requests data from the server with an HTTP GET request.$.get(URL,callback);
The above syntax have the following meaning :
The following example uses the jQuery $.get()
method to make an Ajax request to the "get-demo.php" file using HTTP GET method. It simply retrieves the date and time returned from the server and displays it in the browser without refreshing the page.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Ajax $.get() Method</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.get("get-demo.php", function(data, status){
$("#get_demo").html(data);
alert("Status: " + status);
});
});
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
</style>
</head>
<body>
<div id="get_demo">
<h3>jQuery AJAX get() Method. Load the content and replaced in samepage.</h3>
</div>
<button type="button" class="btn">Click Here (Date & Time)</button>
</body>
</html>
</head>
<body>
The $.post()
method requests data from the server using an HTTP POST request.
$.post(URL,data,callback);
POST requests are identical to GET requests in jQuery. So, generally which method you should use either $.get()
or $.post()
is basically depends on the requirements of your server-side code. The following example uses the $.post()
method to send some data along with the request :
<!DOCTYPE html>
<html>
<head>
<title>jQuery Ajax $.post() Method</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var actionFile = $(this).attr("action");
var formValues = $(this).serialize();
$.post(actionFile, formValues, function(data){
$("#my_result").html(data);
});
});
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
.lable{font-size:14px; font-weight:bold; font-style:italic; clear:both;}
.custon_form{border-radius:3px; margin:5px 0px;}
.result{margin:15px 0px 5px; }
</style>
</head>
<body>
<form action="post-demo.php">
<label class="lable">Name:</label> <br>
<input type="text" name="name" class="custon_form" required /><br>
<label class="lable">Comment: </label><br>
<textarea rows="4" cols="50" name="comment" class="custon_form" required></textarea><br>
<input type="submit" class="btn" value="Send">
</form>
<div id="my_result" class="result"></div>
</body>
</html>