The load() function
The jQuery load() method is used to retrieve an HTML element from the server and place it on an existing web page. The Same-origin policy, or same-origin security policy, allows AJAX requests exclusively from the same domain. The addresses we want to retrieve with AJAX are best written as relative to the origin of the web page so that in case of a domain change all AJAX links remain correct.
The HTML data we retrieve from the server is placed in the target selector. If the selector selects 0 elements, the AJAX request will not be sent. If the selector selects multiple elements, the same data will be loaded into all elements.
In the following example, a list from the data.html file is inserted within the <div> element.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>load() method</title>
<script src="jquery-3.7.0.js"></script>
<script>
$(function () {
$("div").load("data.html");
});
</script>
</head>
<body>
<div>Data placeholder</div>
</body>
</html>
data.html
<!-- data.html --> <ul> <li>First</li> <li>Second</li> <li>Third</li> </ul>
In a case where we want to get just a fragment of an HTML document, we have to specify the element's ID.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>load() Method - Fragment</title>
<script src="jquery-3.7.0.js">
</script>
<script>
$(function () {
$("p").load("data2.html #symbolicList");
});
</script>
</head>
<body>
<h1> Metoda load() - Fragment </h1>
<p>Here a symbolic list will be loadeda</p>
</body>
</html>
data2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<ul id="symbolicList">
<li>First option</li>
<li>Second</li>
<li>Third</li>
</ul>
</body>
</html>
The get() and post() functions
They are used to retrieve data from the server in any format, which are used depending on the following criteria:
- if we are sending large amounts of data in the request, we use post()
- if the request serves to retrieve data, it is recommended to use get()
$.get("address", "data", callbackFunction);
$.post("address", "data", callbackFunction);
- The first parameter is the address to which the request is sent.
- The second parameter is optional and represents the data sent to the server as part of the request. They are usually string type or object literal.
- The third parameter is most often an anonymous function that is called when data arrives from the server and is used to process the received data.
If the data is sent in the form of a string, it must be formatted in query string format.
- The data is in the form of name=value.
- The data is separated by the & character.
- The data must be URL encoded to avoid any forbidden characters.
For this purpose, it's good to use the JavaScript function encodeURIComponent() which returns a URL encoded string.
jQuery offers the serialize() method which is called on the form and gives a query string as a result, based on the names of the form elements and the user's input. If the data is sent as an object literal, you don't need to URL encode the data because
jQuery functions will do the encoding as necessary. The jQuery serialize() method is discussed in more detail later in the manual.
$.get("address", {category: "categoryName"} , callbackFunction);
If we use the get() function, the data will be put in the query string. If we use the post() function, the data will be sent in the body of the request. The third parameter, a function that is called if the request is successfully completed, receives data that the server returned in textual, HTML, XML, or JSON format.
The type of data parameter determines the Content-Type of the response:
- string (can contain primitive data type, HTML fragment, or an entire document)
- root element of the XML document
- JSON object
If an error occurs in the request, we can get error details to correct it more easily. By chaining the error method, we can get error data.
The method accepts three parameters:
- an object of type jqXHR which is a wrapper around the XMLHttpRequest object
- a string with the status: null, timeout, error, abort, parsererror
- a string with the description of the error. Example of errors: Not Found, Bad Request, Forbidden, Method Not Allowed...
<script>
$(document).ready(function(){
$.get('nonexistentFile.html').error(function (jqxhr, status, description) {
alert(status + ', ' + description);
});
});
</script>
Text Data Processing
When sending a response, the server sends a Content-Type header of type "text/plain" so that the data parameter contains pure text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JQuery AJAX - Text data processing</title>
<script src="jquery-3.7.0.js">
</script>
<script>
$(function () {
$.get("Data.txt", function(data){
$("p").text(data);
});
});
</script>
</head>
<body>
<h1>JQuery AJAX - Text data processing</h1>
<p>data will be loaded here</p>
</body>
</html>
HTML Data Processing
When sending a response, the server sends a Content-Type header of type "text/html" so that the data parameter contains an HTML string.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JQuery AJAX - HTML data processing</title>
<script src="jquery-3.7.0.js">
</script>
<script>
$(function () {
$.get("Data.html", function(data){
$("p").text(data);
});
});
</script>
</head>
<body>
<h1>JQuery AJAX - HTML data processing</h1>
<p>HTML will be loaded here</p>
</body>
</html>
XML Data Processing
When sending a response, the server sends a Content-Type header of type "text/xml" so that the data parameter contains a JavaScript XML object made by jQuery and filled with data from the file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JQuery AJAX - XML data processing</title>
<script src="jquery-3.7.0.js">
</script>
<script>
$(function () {
$.get("Data.html", function(data){
$("p").append($(data).find("name").text() + "<br/>");
$("p").append($(data).find("surname").text() + "<br/>");
});
});
</script>
</head>
<body>
JSON Data Processing
When sending a response, the server sends a Content-Type header of type "application/json" so that the data parameter contains a plain object made by jQuery based on the JSON data from the retrieved address.
For retrieving JSON data, there is a separate getJSON() method that takes the same parameters as the get() and post() functions described.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JQuery AJAX - JSON Data Processing</title>
<script src="jquery-3.7.0.js">
</script>
<script>
$(function () {
$.get("http://localhost:1245/MyWebsite/Index", function(data){
$("p").append(data.title + "<br/>");
$("p").append(data.content + "<br/>");
});
});
</script>
</head>
<body>
<h1>JQuery AJAX - JSON Data Processing</h1>
<p>JSON data will be loaded here</p>
</body>
</html>
The ajax() function
The ajax() function combines all previously mentioned functions for working with AJAX. It takes only one parameter, an object literal that contains many options, some of the most useful are:
- url – the address we send the request to
- dataType – the type of data expected from the server: xml, json, jsonp, text, html…
- data – contains the data we send in the request (string or object literal)
- success – a function that is called if the request succeeds, the function receives one parameter, data arrived from the server
- error – a function that is called if the request fails and receives parameters as previously explained
- type – the method of sending the request: get, post…
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>JQuery AJAX – Ajax function</title> <script src="jquery-3.7.0.js"> </script> <script> $(function () { $.ajax({ url: "http://localhost:1245/MyWebsite/Index", dataType: "json", type: "get", success: function(data){ $("p").append(data.title + "<br/>"); $("p").append(data.content + "<br/>"); }, error: function(jqxhr, status, description) { alert(status + " - " + description); } }); }); </script> </head> <body> <h1>JQuery AJAX - JSON Data Processing</h1> <p>JSON data will be loaded here</p> </body> </html>
Ajax and forms
JQuery's Ajax capabilities can be particularly useful when processing forms. There are several advantages such as serialization, client-side validation and so on.
Serialization
In JQuery there are two methods for form serialization, serialize() and serializeArray().
The .serialize() method serializes form data within a query string. To serialize the values of elements, the elements must have a name attribute. Input elements of type checkbox and radio are included only if they are checked.
// Convert form data to query string
$("#form").serialize();
// The following query string is created:
// inputName1=value1&inputName2=value2...
In some situations, applications work better if an array of objects is sent instead of a query string. For this purpose, the JQuery library has a serializeArray() method. It is very similar to the serialize() method, but it produces an array of objects instead of a string.
// Creating an array of objects that contains information from the form
$("#form").serializeArray();