1
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.

flag
What structure should the JSON data have? Just {"firstName":"harry", "lastName":"tester", "toEmail":"[email protected]"}? – Gumbo Aug 10 '09 at 17:15
Yes the data would be in the format you described! thanks for the responses! – Randy Smith Aug 10 '09 at 17:21

1 Answer

2

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"></script>
   <script type="text/javascript" src="http://www.json.org/json2.js"></script>
   <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.

link|flag
2  
That's not going to submit the data in JSON format. – Crescent Fresh Aug 10 '09 at 16:59
As a matter of fact, the serialize function converts form data to a JSON object. – Josh Stodola Aug 10 '09 at 17:01
1  
Josh, the example on jQuery shows otherwise: Looks more like a standard query-string than like JSON. – Jonathan Sampson Aug 10 '09 at 17:04
You guys are right. I've updated the answer accordingly. Thanks! – Josh Stodola Aug 10 '09 at 17:12
Is there anyway you could give me anymore details then this. A full blow example if possible. thanks again – Randy Smith Aug 10 '09 at 17:54
show 2 more comments

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.