RSS
 

Archive for December, 2011

Sample Page for sending JSON data as string to web-service

05 Dec

Just realised it has been a year since I posted anything on here! Time really flies when you’re busy!

I remember when I was first starting off with jQuery, JSON and all that jazz that I struggled to find some simple examples of how to do things like send data to a web-service.

Here is a quick example of how to send some JSON data (as a single post field) to a web service, using jQuery’s post method.

Keep in mind that if you are posting to another domain you may need to use something called jsonP – but if you are just learning, this is a good starting point!

<!DOCTYPE html>
<html>
    <head>
        <title>JSON Web Service Demo</title>
 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
 
        <script type="text/javascript">
            $(document).ready(function() {
 
                //this code will be added to the onclick event
                $('#save_user_button').click(function() {
 
                    //add the values we need for the API to an object
                    var data = new Object;
 
                    //build the object
                    data.guid                   = $('#guid').val();
                    data.defaultallocation      = $('#projecttype').val();
                    data.email                  = $('#email').val();
                    data.username               = $('#username').val();
                    data.fullname               = $('#fullname').val();
 
                    //turn the object in to a JSON string
                    var myJson = JSON.stringify(data);
 
                    var url = "http://testurl/service/user";
 
                    //call the post
                    $.post(url, {jsonUser : myJson}, function(myResult) {
                        alert(myResult)
                    });
 
                });
 
            });
        </script>
 
    </head>
    <body>
        <div>
            <table>
 
                <tr>
                    <td>Project Type</td>
                    <td><input id="projecttype"/></td>
                </tr>
 
                <tr>
                    <td>GUID</td>
                    <td><input id="guid"/></td>
                </tr>
 
                <tr>
                    <td>User Name</td>
                    <td><input id="username"/></td>
                </tr>
 
                <tr>
                    <td>Full Name</td>
                    <td><input id="fullname"/></td>
                </tr>
 
                <tr>
                    <td>Email</td>
                    <td><input id="email"/></td>
                </tr>
 
            </table>
 
            <input type="button" id="save_user_button" value="Save"/>
 
        </div>
    </body>
</html>