Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit JSON Data by Request Body in jQuery?

I am not expert in jQuery, consider me fresher. Here is my code which one not responsible for jQuery JSON data submission by Request Body.

<!doctype html>
<html lang="en">
<head>
    <title>jQuery Data submitted by JSON Body Request</title>
    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $.ajax({
        url : "/",
        type: "POST",
        data: [
            {id: 1, name: "Shahed"}, 
            {id: 2, name: "Hossain"}
        ],
        contentType: "application/json; charset=utf-8",
        dataType   : "json",
        success    : function(){
            console.log("Pure jQuery Pure JS object");
        }
    });

    </script>
</head>
<body>
    <p>
        Example of submission JS Object by JSON Body Request<br/>
        Its could submitted mass amount of data by Message body<br/>
        It's secured and faster than any data submission .
    </p>
</body>
</html>

Post Source appeared:

Shahed=undefined&Hossain=undefined

But desired Post Source is:

[{"id":1,"name":"Shahed"},{"id":2,"name":"Hossain"}]

How do I get the desired Post Source for each Request Body?

like image 433
Śhāhēēd Avatar asked Jan 18 '14 07:01

Śhāhēēd


1 Answers

Here is the right code for your desired out put.

$.ajax({
        url : "/",
        type: "POST",
        data: JSON.stringify([
            {id: 1, name: "Shahed"}, 
            {id: 2, name: "Hossain"}
        ]),
        contentType: "application/json; charset=utf-8",
        dataType   : "json",
        success    : function(){
            console.log("Pure jQuery Pure JS object");
        }
    });

Your must convert JS Object to String and JSON.stringify(JSObject) is the method responsible for that.

like image 114
Śhāhēēd Avatar answered Sep 28 '22 09:09

Śhāhēēd