← Back to Chapters

jQuery $.get() and $.post() Methods

? jQuery $.get() and $.post() Methods

? Quick Overview

jQuery provides simplified AJAX helper methods such as $.get() and $.post() to communicate with servers using HTTP GET and POST requests.

? Key Concepts

  • GET is used to retrieve data.
  • POST is used to send data.
  • Both methods are asynchronous.
  • Error handling is done using .fail().

? Syntax / Theory

? View Code Example
// jQuery AJAX helper method syntax
$.get(url, [data], [callback], [dataType]);
$.post(url, [data], [callback], [dataType]);

? Live Example – GET

Click the button to GET data here.
? View Code Example
// Fetch data from server using GET
$('#getBtn').click(function() {
$.get('https://jsonplaceholder.typicode.com/posts/1', function(data) {
$('#getResult').text(JSON.stringify(data, null, 2));
}).fail(function() {
$('#getResult').text('Error retrieving data.');
});
});

? Live Example – POST

Click the button to POST data here.
? View Code Example
// Send data to server using POST
$('#postBtn').click(function() {
$.post('https://jsonplaceholder.typicode.com/posts',
{ title: 'foo', body: 'bar', userId: 1 },
function(data) {
$('#postResult').text('Response:\n' + JSON.stringify(data, null, 2));
})
.fail(function() {
$('#postResult').text('Error sending data.');
});
});

? Interactive Example – User Form

Try sending your own custom data to the server using $.post():

Server response will appear here.

? Live Output / Explanation

The GET request retrieves a JSON object from the server, while the POST request sends data and receives a response object created on the server.

? Use Cases

  • Fetching user profiles
  • Submitting forms asynchronously
  • Loading dashboard data dynamically
  • Creating or updating records

✅ Tips & Best Practices

  • Use GET for read-only operations.
  • Use POST for sensitive or large data.
  • Always handle errors with .fail().

? Try It Yourself

  • Change the API endpoint to /users/1.
  • Add more fields to the POST request.
  • Use .done() and .always().