Jacques
Jacques

Reputation: 3774

Why when sending data over AJAX, do you have to JSON.stringify() your objects?

JSON stands for javascript object notation (as I'm sure you're aware), so why, when sending json via ajax do you need to turn it into a string to send it? Is it simply a formatting thing, or what?

This may belong in another place, if so, let me know, I'll close it and move it.

Obviously, I'm not looking for opinions, I'd like to know the actual answer.

Just to make sure I'm clear, I understand what JSON.stringify() does, and its counterpart JSON.parse(). I just want to know, why using stringify is required.

Thanks!

Upvotes: 9

Views: 4761

Answers (3)

heyfranksmile
heyfranksmile

Reputation: 309

When sending data to a web server, the data has to be a string.

That's why we are using JSON.stringify() function to convert data to string and send it via XHR request to the server.

        // Creating a XHR object 
        let xhr = new XMLHttpRequest();
        let url = "submit.php"; 

        // open a connection 
        xhr.open("POST", url, true); 

        // Set the request header i.e. which type of content you are sending 
        xhr.setRequestHeader("Content-Type", "application/json"); 

        // Converting JSON data to string 
        var data = JSON.stringify({ "name": name.value, "email": email.value }); 

        // Sending data with the request 
        xhr.send(data);  

Upvotes: 0

Quentin
Quentin

Reputation: 944149

when sending json via ajax do you need to turn it into a string to send it?

If it isn't a string, then it isn't JSON in the first place.

JSON is a text based data format. HTTP is a text based communications protocol.

JSON stands for javascript object notation

JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.

Upvotes: 16

alcfeoh
alcfeoh

Reputation: 2267

AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.

Upvotes: 3

Related Questions