$.ajax() Method in jQuery
$.ajax()
method is used to perform an (AJAX)asynchronous HTTP request.
- Ajax is not a programming language.
- AJAX is a combination of JavaScript XMLHttpRequest and XML.
- We can updating parts of a web page, without refreshing the whole page.
In jQuery have several settings for Ajax request. All settings are optional. The following syntax for some common Ajax request.
Syntax
$.ajax({ url:"get_details.php", type:"post", data:{id:25}, dataType:"html", beforeSend:function(xhr){ }, success:function(res,txt,xhr){ }, error:function(xhr, txt, err){ }, complete:function(xhr,txt){ } });
- url - Request URL.
- type - Type of Request (GET ot POST).
- data - Data to be sent to the server.
- dataType - Server response data type (xml,html,json,script,text).
- beforeSend - A function to execute before send request.
- success - A function to execute when the request succeeds.
- error - A function to execute if the request fails.
- complete - A function to execute when the request finishes.
res - response data , xhr - XMLHttpRequest , txt - textStatus , err - errorThrown
Example:
The following example show, how to send parameters and get data from sample.php
using jQuery get()
method.
<html> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <body> <div id='res'></div> </body> <script> $(document).ready(function(){ $.ajax({ url:"sample-file.php", type:"post", data:{name:"Tom",age:25}, beforeSend:function(){ $("#res").text("Processing..."); }, success:function(res){ $("#res").text("Data Post Successfully : "+res); }, complete:function(xhr,status){ //complete function run when the request is finished(success or error). } }); }); </script> </html>
sample-file.php
<?php echo $_POST["name"]." Age is ".$_POST["age"].". This is Sample Text from external PHP File"; ?>
Output :
Data Post Successfully : Tom Age is 25. This is Sample Text from external PHP File