1

When making an AJAX POST call to PHP backend, is it not necessary to JSON.stringify the POST params/request object ? Can it be sent directly as JS object ? What is the difference in handling the same on the PHP side?

Any best practices for the request object.

testndtv
  • 43,898
  • 91
  • 265
  • 396
  • 1
    Particular answer is here - https://stackoverflow.com/questions/32570523/why-when-sending-data-over-ajax-do-you-have-to-json-stringify-your-objects – user1597430 Dec 22 '18 at 05:11

1 Answers1

1
  1. Is it not necessary to JSON.stringify the POST params/request object?

The general answer is: an object should aways be serialized (eg: JSON.stringify) to be sent through network. But if you are using some JavaScript frameworks which can serialize an object to a JSON string (or byte stream) automatically, then you can pass your object to the framework directly and let the framework handle it.

  1. Can it be sent directly as JS object?

No, any object should be serialized to a byte stream (or string) to be sent to the server side.

Here is about What is serialization?

  1. What is the difference in handling the same on the PHP side?

On PHP side, you just de-serialize the byte stream you received and you get the original object.

shawn
  • 3,838
  • 11
  • 24
  • Thanks...But I am a bit confused...when you say, we can send request payload without stringifying (though we should), does it not mean it is actually possible to send without serializing ? – testndtv Dec 22 '18 at 05:55
  • You should always serialize an object to send it through network. If your framework helps to serialize an object automatically, you can just pass the object to the framework. – shawn Dec 22 '18 at 08:08
  • @testndtv I never mean "we can send request payload without stringifying". updated. – shawn Dec 22 '18 at 08:11
  • Thanks. When you say "framework which can serialize an object to a JSON ", I assume you are referring to the backend framework here e.g. PHP or somethin. Is that correct ? – testndtv Dec 22 '18 at 09:53
  • There are plenty of JavaScript frameworks – shawn Dec 22 '18 at 11:07