Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  189] [ 7]  / answers: 1 / hits: 29533  / 11 Years ago, thu, august 22, 2013, 12:00:00

Regarding this line:



var data = encodeURIComponent(JSON.stringify(object_literal));


I don't understand why this is being URI encoded.



Later data will be sent via ajax POST.



I understand that URLs, particularly the one you can see in the browser address bar require special characters as described here:



http://www.blooberry.com/indexdot/html/topics/urlencoding.htm



But what exactly does this have to do with Ajax posting?



Do both the url address bar and the internal ajax post utilize the same mechanism?


More From » php

 Answers
9

It all depends on the content type.



Normally when a <form> uses the HTTP method POST then the form values are URL Encoded and placed in the body of the request. The content type header looks like this:



content-type: application/x-www-form-urlencoded


Most AJAX libraries will do this by default since it is universally accepted among web servers. However, there is nothing preventing you from simply serializing the data as JSON or XML and then sending it with a different content type.



content-type: application/json


or



content-type: text/xml


It's worth noting that the payload has nothing to do with AJAX! Under the hood they are all using the XmlHttpRequest object to send an HTTP request asynchronously to the server. It doesn't matter if you send Plain Text, JSON, XML, or even raw binary data so long as you tell the server how to interpret those bits.



The url encoding is purely a historical artifact of how <form> elements posted their data to the server before AJAX was around.


[#76214] Wednesday, August 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carolynt

Total Points: 252
Total Questions: 98
Total Answers: 109

Location: French Southern and Antarctic Lands
Member since Sat, Oct 31, 2020
4 Years ago
;