jQuery ajax()

Introduction

Change the text of a <div> element using an AJAX request:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//from ww  w. j a  v a2  s .co m
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url: "ajax.txt", success: function(result){
      $("#div1").html(result);
    }});
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Here</h2></div>

<button>Get External Content</button>

</body>
</html>

The ajax() method is used to perform an AJAX (asynchronous HTTP) request.

$.ajax({name:value, name:value, ... })

The parameters specifies one or more name/value pairs for the AJAX request.

Possible names/values in the table below:

Name Value Description
async A Boolean value whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr)A function run before the request is sent
cache A Boolean value whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function run when the request is finished (after success and error functions)
contentTypeString content type to use when sending data to the server. Default is: "application/x-www-form-urlencoded"
contextthis value "this" value for all AJAX related callback functions
data Object data to be sent to the server
dataFilter(data,type) A function handle the raw response data of the XMLHttpRequest
dataType String The data type expected of the server response.
error(xhr,status,error)A function run if the request fails.
global A Boolean valuewhether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean valuewhether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A stringoverriding the callback function in a jsonp request
jsonpCallback A stringa name for the callback function in a jsonp request
password A stringpassword to be used in an HTTP access authentication request.
processDataA Boolean value whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset A string charset for the request
success(result,status,xhr) A functionrun when the request succeeds
timeoutA number local timeout in milliseconds for the request
traditionalA Boolean value whether or not to use the traditional style of param serialization
type A string the type of request. (GET or POST)
urlA string URL to send the request to. Default is the current page
username A string a username to be used in an HTTP access authentication request
xhrA function used for creating the XMLHttpRequest object



PreviousNext

Related