RSS
 

Posts Tagged ‘json’

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>
 
 

Loading JSON data – the EASY way!

18 Nov

json160A few weeks ago I wrote a blog post about using jQuery and JSON to automatically load data from a JSON file in to name-matched controls on an HTML page.

It is only now that I realise quite how powerful this is!

The great thing about it is that you do not have to edit your data-load function if you add a new field to the database. Because the jQuery function loops through all the fields in the JSON data, it will automatically insert the values in to the correct fields, providing those fields are named the same as the html form controls.

Here is the code again for those who dont want to check back.

$.getJSON("/yourJson.js, function(myJson){
	$.each(myJson.rows, function(i,item) {
		 for (prop in item) {
		 	 $('#' + prop).val(item[prop]);
		 }
	});
});
 

Inserting JSON data in to name-matched controls

01 Sep

Thought this might be handy… This loop will insert the values from a JSON object in to text boxes.

It loops around each key-pair and inserts the value if there is a text box with an ID that matches the key name.

This is the JSON data: (yourJson.js)

{"page":1,"total":1,"records":1,"paging":20,"rows":[
{"clipId":"14792","barcode":"02528","title":"My Project Sample","format":"DigiBeta","source":"1242",
"runningTime":"14 Mins","location":"Library","timeCode":"10:00:00","cUser":"Sam",
"cDate":"1 Jan 2007","mUser":"Sam","mDate":"1 Jan 2008"}]}

This is the form HTML:

<form>
	<table>
		<tr>
			<th>Clip Id</th>
			<td><input id='clipId'></td>
		</tr>
		<tr>
			<th>Barcode</th>
			<td><input id='barcode'></td>
		</tr>
		<tr>
			<th>Title</th>
			<td><input id='title'></td>
		</tr>
		<tr>
			<th>Format</th>
			<td><input id='format'></td>
		</tr>
		<tr>
			<th>Source</th>
			<td><input id='source'></td>
		</tr>
		<tr>
			<th>Running Time</th>
			<td><input id='runningTime'></td>
		</tr>
		<tr>
			<th>Location</th>
			<td><input id='location'></td>
		</tr>
		<tr>
			<th>Time Code</th>
			<td><input id='timeCode'></td>
		</tr>
	</table>
</form>

This is the jQuery:

	$.getJSON("/yourJson.js, function(myJson){
		$.each(myJson.rows, function(i,item) {
		    for (prop in item) {
				$('#' + prop).val(item[prop]);
		    }
		}); 
	});
 
 

Creating JSON data from MySQL in PHP

24 Aug

Here is a quick post that demonstrates how to create some neat JSON data from MySQL using PHP. The script is really simple, and has been working well for me over the last few weeks.

If anything is confusing, it might be worth checking out the previous post about creating XML data from PHP. It explains things in more detail and will help if you are not familiar…

//set up the php headers so that the page doesnt cache etc
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: text/json");
 
$jsonArray->page = $page; 
$jsonArray->total = $totalPages;
$jsonArray->records = $recordCount; 
 
$i=0; 
while ($row = $db->fetch_array($countRows)) {
	$jsonArray->rows[$i]['id']=$row['userAccountId']; 
	$jsonArray->rows[$i]['userName']=$row['userName'];
	$jsonArray->rows[$i]['fullName']=$row['fullName'];
	$jsonArray->rows[$i]['accessCode']=$row['accessCode'];
	$jsonArray->rows[$i]['email']=$row['email'];
	$jsonArray->rows[$i]['addedBy']=$row['addedBy'];
	$jsonArray->rows[$i]['addedDate']=$row['addedDate'];
	$jsonArray->rows[$i]['modifiedBy']=$row['modifiedBy'];
	$jsonArray->rows[$i]['modifiedDate']=$row['modifiedDate'];
	$i++; 
} 
 
echo json_encode($jsonArray);

The above code will create the following style JSON output.

{"page":1,"total":1,"records":"3","rows":[
{"id":"1","userName":"demo","fullName":"Demo User","accessCode":"","email":"demo@myexample.com","addedBy":"1","addedDate":"2009-05-02 00:00:00","modifiedBy":"10","modifiedDate":"2009-06-04 00:00:00"},
{"id":"2","userName":"sam","fullName":"Sam Lasagne","accessCode":"","email":"sam@myexample.com","addedBy":"2","addedDate":"2009-05-02 00:00:00","modifiedBy":"2","modifiedDate":"2009-08-02 00:00:00"},
{"id":"10","userName":"adrian","fullName":"Adrian Spaghetti","accessCode":"","email":"adrian@myexample.com","addedBy":"1","addedDate":"2009-05-02 00:00:00","modifiedBy":"2","modifiedDate":"2009-09-01 00:00:00"}
]}