jQuery AJAX Differences Between GET vs POST

Share this article

Quite a few people have been asking me the question “what is the difference between GET and POST when I am specifying an AJAX request?”. These are the key differences between GET and POST when you are specifying an AJAX request using jQuery. Related posts:

GET vs POST

  • A GET request is used to get data from the server.
  • A POST request is used for modifying data on the server.

When to use GET

If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.
Characteristics of GET:
  • Use GET for safe actions and POST for unsafe actions.
  • GET requests can be cached
  • GET requests can remain in the browser history
  • GET requests can be bookmarked
  • GET requests can be distributed & shared
  • GET requests can be hacked
W3.org GET Method Definition

When to use POST

If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
  • Use POST when dealing with long requests – if you’re sending large amounts of data, or sensitive data over HTTPS, you will want to use POST. Some browser such as Internet Explorer place a limit on the URL string so this may break the action of some forms if you use GET.
You may consider using POST for the following actions:
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles
  • Providing a block of data, such as the result of submitting a form, to a data-handling process
  • Extending a database through an append operation
  • Annotation of existing resources
W3.org POST Method Definition

GET vs POST in AJAX calls

Unless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data). This means that GET requests are more responsive – something you need in AJAX environments! Because “Ajax” requests are subject to the same origin policy there is limited security risks when using GET instead of POST. Use GET to “GET” information from the server such as loading a JavaScript file (AJAX shorthand function $.getScript() can be used to do this) or loading a JSON file (AJAX shorthand function $.getJSON() can be used to do this). jQuery AJAX Functions that use GET as default: $.get(), $.getScript(), $.getJSON(), .load() jQuery AJAX Functions that use POST as default: $.post() Example GET AJAX Call – Calling a PHP script to get the number of twitter followers.
$.ajax({
  url: 'getTwitterFollowers.php',
  type: 'GET',
  data: 'twitterUsername=jquery4u',
  success: function(data) {
	//called when successful
	$('#ajaxphp-results').html(data);
  },
  error: function(e) {
	//called when there is an error
	//console.log(e.message);
  }
});
View Demo Example POST AJAX Call – Submitting a login form.
var $form = $("#myForm");
    var url = $form.attr("action") + "?" + $form.serialize();
    $("#" + id).html(url);

$.ajax({
	type: "POST",
	url: action,
	data: $form,
	success: function(response)
	{
		if(response == 'success')
			$("#myForm").slideUp('slow', function() {
				$("#msg").html("You have logged in successfully!");
			});
		else
			$("#msg").html("Invalid username and/or password.");
	}
});

Further Readings

Form Submission Example This example doesn’t really apply to AJAX as these requests happen behind the scenes but may help you understand further what is happening between the different request types. When using GET a HTTP request is generated and passes the data to the web server as a set of encoded parameters appended to the URL in a query string. For instance, it would be a bad idea to use GET for a login form submission as the login details would show in the address bar.
GET /login.php?username=user&password=12345 HTTP/1.1
Host: domain.com
But if we used POST the parameters would be passed within the body of the HTTP request, not in the URL. This would happen behind the scenes between the browser and the web server.
POST /login.php HTTP/1.1
Host: domain.com
username=user&password=12345

GET Caching GET is intended to be used when you are reading information to display on the page. Browsers will cache the result from a GET request and if the same GET request is made again then they will display the cached result rather than rerunning the entire request.
REST – The “RESTful” Client Server Architecture
HTTP, for example, has a very rich vocabulary in terms of verbs (or “methods”), URIs, Internet media types, request and response codes, etc. REST uses these existing features of the HTTP protocol, and thus allows existing layered proxy and gateway components to perform additional functions on the network such as HTTP caching and security enforcement.
Read about “Representational State Transfer” (REST): http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_example:_the_World_Wide_Web
REST – The “RESTful” Web Services (API)
It is a collection of resources, with four defined aspects: the base URI for the web service, such as http://example.com/resources/ the Internet media type of the data supported by the web service. This is often JSON, XML or YAML but can be any other valid Internet media type. the set of operations supported by the web service using HTTP methods (e.g., POST, GET, PUT or DELETE). The API must be hypertext driven.[11]
http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services

Conclusion

Well I hope that you have a clear idea of when to use GET and when to use POST. If your still unsure or want to inspect what’s happening behind the scenes of your AJAX calls use a tool like Firebug NET Panel to see where your data is being sent (such as in the header) the type of request. Other than that, happy Ajax’ing!

Frequently Asked Questions (FAQs) about AJAX GET and POST Methods

What are the key differences between AJAX GET and POST methods?

AJAX GET and POST methods are both used to send data to the server. The main difference lies in how they send this data. GET appends data to the URL in name/value pairs, making it visible in the browser’s address bar. It’s ideal for sending small amounts of data. POST, on the other hand, sends data within the body of the HTTP request, making it invisible to the user. It’s suitable for sending large amounts of data or sensitive information.

When should I use AJAX GET method over POST method?

The GET method is best used when you need to retrieve data from the server that doesn’t affect the server’s state. It’s also ideal when you need to bookmark or share the URL, as the data is appended to the URL. However, it’s not suitable for sending sensitive data as it’s visible in the URL.

Can I send sensitive data using AJAX POST method?

Yes, the POST method is designed to send data within the body of the HTTP request, making it invisible to the user. This makes it suitable for sending sensitive data or large amounts of data. However, while the data isn’t visible in the URL, it’s not encrypted and could be intercepted unless you’re using HTTPS.

Is there a size limit for data sent using AJAX GET and POST methods?

Yes, the GET method has a size limit because it appends data to the URL. The limit varies by browser but is typically around 2000 characters. The POST method, on the other hand, doesn’t have a defined limit as it sends data within the body of the HTTP request.

Can I use both AJAX GET and POST methods in a single application?

Yes, you can use both methods in a single application. You might use the GET method to retrieve data from the server and the POST method to send data to the server. The choice depends on the specific requirements of your application.

How can I handle errors in AJAX GET and POST methods?

Both methods provide error handling mechanisms. You can use the .fail() method in jQuery to handle any errors that occur when the request is made. This method is called when the request fails, and it takes a function as an argument that will be executed in the event of an error.

Are AJAX GET and POST methods secure?

While the POST method is more secure than the GET method because it doesn’t expose data in the URL, neither method provides encryption. To ensure data security, you should use HTTPS, which encrypts the data sent between the client and server.

Can I send data to a different domain using AJAX GET and POST methods?

By default, AJAX requests are subject to the same-origin policy, which means you can only make requests to the same domain that your page is on. However, you can make cross-domain requests using JSONP or CORS, but these methods have their own security implications and should be used with caution.

How can I cancel an AJAX GET or POST request?

You can cancel an AJAX request by calling the .abort() method on the jqXHR object returned by $.ajax(). This will immediately terminate the request and trigger the error callback.

Can I send files using AJAX GET and POST methods?

You can’t send files using the GET method because it appends data to the URL. However, you can send files using the POST method with the help of the FormData object, which allows you to send form data, including files, as key-value pairs to the server.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week