JSON stringify() Method

Why JSON.stringify()

You cannot send an object to a web-server, so you have to convert your object to a string. Thus JSON.stringify() comes in action.

Note: String is the only data type to exchange data between a browser and a web-server.

Sending Data From Client-Side to Server-Side

From the client-side, the object has to be converted to a string and send to the web-server. Whereas, In a web-server, you will catch the transmitted string from the client-side and convert it to an object to work with it.

Note: While sending data to a web-server jQuery will automatically convert your object to a string. So, you don't have to convert it explicitly by using JSON.stringify().

In the following example, we will convert an object to a string by using JSON.stringify().


HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <h1>JSON.stringify()</h1> <p id="point"></p> <button onclick="myFunction()">Send to Server</button> <script> var x = document.getElementById("point"); var data = { name: "Mike", age: 36}; function myFunction(){ $.post("/json-name.php",{ myData: JSON.stringify(data) },function(serverData){ x.innerHTML = serverData; }); } </script> </body> </html>



Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author