views:

2982

answers:

1

Hello, I have some data that I need converted to JSON format and then POSTed with a Javascript function.

<body onload="javascript:document.myform.submit()">
<form action="https://www.test.net/Services/RegistrationService.svc/InviteNewContact" method="post" name="myform">
<input name="firstName" value="harry" />
<input name="lastName" value="tester" />
<input name="toEmail" value="[email protected]" />
</form>

This is the way the post looks now. I need it submit the values in JSON format and do the POST with javascript. Hope this makes sense.

+4  A: 

Here is an example using jQuery...

 <head>
   <title>Test</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
   <script type="text/javascript" src="http://www.json.org/json2.js"&gt;&lt;/script&gt;
   <script type="text/javascript">
     $(function() {
       var frm = $(document.myform);
       var dat = JSON.stringify(frm.serializeArray());

       alert("I am about to POST this:\n\n" + dat);

       $.post(
         frm.attr("action"),
         dat,
         function(data) {
           alert("Response: " + data);
         }
       );
     });
   </script>
</head>

The jQuery serializeArray function creates a JSON object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.

Josh Stodola
That's not going to submit the data in JSON format.
Crescent Fresh
As a matter of fact, the serialize function converts form data to a JSON object.
Josh Stodola
Josh, the example on jQuery shows otherwise: Looks more like a standard query-string than like JSON.
Jonathan Sampson
You guys are right. I've updated the answer accordingly. Thanks!
Josh Stodola
Is there anyway you could give me anymore details then this. A full blow example if possible. thanks again
You got it, Randy!
Josh Stodola
Josh I wish you would have left the original code in also. Showed New and Old Code.
Gutzofter