JQuery

Jquery Ajax and Json

jQuery AJAX and JSON: Dynamic Data Loading & Interaction

What is AJAX?

  • AJAX = Asynchronous JavaScript and XML.

  • Lets you communicate with a server without reloading the whole webpage.

  • Fetch or send data dynamically and update the page content smoothly.

What is JSON?

  • JSON (JavaScript Object Notation) is a lightweight data format.

  • Used to exchange data between client and server.

  • Easy to read/write by humans and machines.


jQuery AJAX Basics

jQuery provides convenient methods to send HTTP requests:

Common AJAX Methods

Method Description Example
$.ajax() Full configurable AJAX request Most flexible method
$.get() Sends a GET request Simplified GET request
$.post() Sends a POST request Simplified POST request
$.getJSON() Sends GET request expecting JSON response Automatically parses JSON

Simple AJAX GET Example

Fetch JSON data from a server and display it:

html
<button id="loadData">Load Data</button>
<div id="result"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(
'#loadData').click(function() {
$.getJSON('https://jsonplaceholder.typicode.com/users', function(data) {
let output = '<ul>';
$.each(data, function(index, user) {
output += `<li>${user.name}${user.email}</li>`;
});
output += '</ul>';
$('#result').html(output);
});
});
</script>


Using $.ajax() for More Control

js
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
data: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }),
contentType: 'application/json; charset=UTF-8',
success: function(response) {
console.log('Post created:', response);
},
error: function() {
alert('Error sending data.');
}
});

Important AJAX Options

  • url: URL to request.

  • method or type: GET, POST, PUT, DELETE, etc.

  • data: Data to send to server (object or string).

  • dataType: Expected response format (e.g., ‘json’, ‘xml’, ‘text’).

  • success: Callback on success.

  • error: Callback on error.


Handling JSON Data

  • jQuery automatically parses JSON responses if dataType: 'json' or when using $.getJSON().

  • You can easily convert JS objects to JSON strings using JSON.stringify().

  • Parse JSON strings using JSON.parse() if needed.


Summary

  • AJAX lets you load and send data without reloading the page.

  • JSON is the most common format for exchanging data.

  • jQuery simplifies AJAX requests with easy methods and automatic JSON handling.

Leave a Reply

Your email address will not be published. Required fields are marked *