Sachin
Sachin

Reputation: 1708

Difference between POST data via HTTP <form> and via AJAX in terms of data encoding

Can anyone please explain the main difference between submitting data via traditional HTTP <form> and via AJAX in terms of data encoding?

Actually I am facing data losing issue while sending data to the server via AJAX. Everything after &nbsp; is lost.

If I send following piece of data to the server via jQuery AJAX

<p>test 1</p>
<p>&nbsp;</p>
<p>test 2</p>

I get following truncated data on the server

<p>test 1</p>
<p>

But if I send the same data via regular HTTP POST form submission, then the entire data is reached at the server.

To check myself how the data is being encoded by regular form submission, I changed form's method from POST to GET and found that the above data is encoded as (extracted from the query string)

<p>test+1<%2Fp>%0D%0A<p>%26nbsp%3B<%2Fp>%0D%0A<p>test+2<%2Fp>

So does it mean that HTTP form does this encoding automatically?

And if we have to send this data to server via AJAX, then we must have to encode it using some encoding function e.g. encodeURIComponent()?

I used encodeURIComponent() and found that the entire data is successfully reached at the server just like a normal HTML form submission.

Can anyone please shed light on this topic with some good details?

Upvotes: 1

Views: 90

Answers (1)

Quentin
Quentin

Reputation: 944560

HTML forms will submit the data in form fields according to one of three standards based on the value of the enctype field.

Ajax will let you send a string that you can format however you like. You can also pass certain kinds of object which will get encoded using some standard (e.g. a FormData object will get encoded using the same multipart format you can select with enctype in a form.

encodeURIComponent will escape special characters for a query string or application/x-www-form-urlencoded request in the same way that a form will by default or if you set the enctype to application/x-www-form-urlencoded. You should run it over every key and value in your string if you are using it to encode data manually. You can use the URLSearchParams object instead though.

const html = `<p>test 1</p>
<p>&nbsp;</p>
<p>test 2</p>`;
const data = new URLSearchParams();
data.append("data", html);
const response = await fetch("http://example.com", { method: "POST", body: data });
const responseData = await response.json();
console.log(responseData);

Since you mentioned jQuery, you can pass that a plain object:

const html = `<p>test 1</p>
<p>&nbsp;</p>
<p>test 2</p>`;
const data = { data: html };
const response = await jQuery.ajax("http://example.com", { method: "POST", data: data });
console.log(response);

Upvotes: 2

Related Questions