3

I am trying to get data from my form and then send it to a servlet. But then I notice that the json object that I am getting after serializing my form is not a valid json object. What could I be doing wrong? This is what I tried so far.

<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
      event.preventDefault();
      var data = $("#register").serialize().split("&");
      var obj={};
        for(var key in data)
        {
            console.log(data[key]);
            obj[data[key].split("=")[0]] = data[key].split("=")[1];
        }

        console.log(obj);
// store json string
     $.ajax({
            type: "POST",
            url: "HomeServlet",
            dataType: "text",
            contentType: "application/json",
            data:{"res":obj},
            success: function(data){
                console.log(data);
            },
            error:function(){
                console.log("error");
            },

        });
});

</script>

The json object that i am getting from the form is -

{
    apiname: "jdjdj",
    apiendpoint: "sdjsdj",
    apiversion: "djdjd",
    source: "internet"
}

This is what I want -

{
    "apiname": "jdjdj",
    "apiendpoint": "sdjsdj",
    "apiversion": "djdjd",
    "source": "internet"
}
Rachel
  • 173
  • 4
  • 12
  • 1
    JSON.stringify({ res: obj}) – Doomenik Jul 24 '17 at 06:40
  • try var new_data = JSON.stringify(data); – Aniket Pawar Jul 24 '17 at 06:40
  • Possible duplicate of [Convert form data to JavaScript object with jQuery](https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery) – Kirill Jul 24 '17 at 06:43
  • 1
    Possible duplicate of [Convert JS object to JSON string](https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – Zico Jul 24 '17 at 06:46
  • Possible duplicate of [Convert JSON String to Object - jquery](https://stackoverflow.com/questions/23311182/convert-json-string-to-object-jquery) – Durgpal Singh Jul 24 '17 at 06:48

5 Answers5

0

There is nothing wrong with the json you Got .

Just stringify it to get the desired object

var myJSON1 = JSON.stringify(data);

this will work

Viplock
  • 3,259
  • 1
  • 23
  • 32
0

YOu may try it

JSON.stringify(json_data);
vjy tiwari
  • 843
  • 1
  • 5
  • 17
0

As others have noted, your passing a raw javascript object. What you must do is convert this object prior to sending it over the wire.

JSON.stringify(json_data);
enjoylife
  • 3,801
  • 1
  • 24
  • 33
0

please use JSON.stringify(obj, undefined, 2);

Uddhav P. Gautam
  • 7,362
  • 3
  • 47
  • 64
-1

Instead of this foreach loop only use serializeArray() then json_parse() these two functions will work for you.

var data = $("#register").serializeArray();
var obj= JSON_parse(JSON_stringify(data));
Osama
  • 2,912
  • 1
  • 12
  • 15