emailconfirmed, nsInternRO, nsInternRW, Administrators
3,356
edits
mNo edit summary |
mNo edit summary |
||
(25 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
This article has been created by Luís Filipe Couto (thanks!). Please feel free to add or correct. | |||
There's also an article here: [[IFD:WApplications/Vortraege/APIs_JSON]] | |||
I'm assuming that you are familiar with [[HTML]], [[CSS]], [[JavaScript]] and [[PHP]] for this article. | |||
== JSON Introduction == | == JSON Introduction == | ||
Line 52: | Line 55: | ||
==Pratical Examples with [[JavaScript]]== | ==Pratical Examples with [[JavaScript]]== | ||
===Fetch and Include JSON File=== | ===Fetch and Include JSON File=== | ||
<p>I will show now, how to use [[JavaScript]] to print JSON files on a [[HTML]] page. I will use the [ | <p>I will show now, how to use [[JavaScript]] to print JSON files on a [[HTML]] page. I will use the [http://web.uni-weimar.de/medien/wiki/JSON#Twitter_API_Introduction Twitter API] to get a JSON file.</p> | ||
[http://twitter.com/statuses/public_timeline.json http://twitter.com/statuses/public_timeline.json] this link allow us to download a JSON file with the last 20 public tweets on [http://www.twitter.com Twitter]. Due security reasons [http://en.wikipedia.org/wiki/Cross-site_scripting (XSS)], we can not fetch the file with using XmlHttpRequest ([[AJAX]]) directly as so, we include it directly in the HTML page: | [http://twitter.com/statuses/public_timeline.json http://twitter.com/statuses/public_timeline.json] this link allow us to download a JSON file with the last 20 public tweets on [http://www.twitter.com Twitter]. Due security reasons [http://en.wikipedia.org/wiki/Cross-site_scripting (XSS)], we can not fetch the file with using XmlHttpRequest ([[AJAX]]) directly as so, we include it directly in the HTML page: | ||
Line 102: | Line 105: | ||
</source> | </source> | ||
<p>Because JSON is natively Javascript we don't need to parse it, in this particular example, and we can itinerate it's values directly using the dot syntax.</p> | <p>Because JSON is natively Javascript we don't need to parse it, in this particular example, and we can itinerate it's values directly using the dot syntax.</p> | ||
---- | |||
===Create a JSON Object=== | ===Create a JSON Object=== | ||
So far we saw how to fetch and include an external JSON File and how to iterate and print a JSON object, but how do we create a JSON of our own? Since JSON was originally made from Javascript, to create an JSON all we need to do, it's to declare it: | So far we saw how to fetch and include an external JSON File and how to iterate and print a JSON object, but how do we create a JSON of our own? Since JSON was originally made from Javascript, to create an JSON all we need to do, it's to declare it: | ||
Line 165: | Line 169: | ||
<li>publishing, modifying or destroying data on Twitter requires the POST request.</li></ul> | <li>publishing, modifying or destroying data on Twitter requires the POST request.</li></ul> | ||
<li>A command-line is all you need to interact with the Twitter API</li> | <li>A command-line is all you need to interact with the Twitter API</li> | ||
<li>There are [http://dev.twitter.com/pages/libraries Twitter API libraries] for almost any language</li> | <li>There are [http://dev.twitter.com/pages/libraries Twitter API libraries] for almost any language</li></ul></p> | ||
==Create a Small Twitter Client== | |||
<p>Since it's so easy to use the Twitter's API, i'm going to show here how to create a small twitter client. I'm going to do some extra steps so that i can refer a few more things about JSON and Twitter</p> | |||
<p>So the process i'm going to use is:</p> | |||
<ol> | |||
<li>[[#Get the JSON File with PHP and cURL]]</li> | |||
<li>[[#Print the tweets]]</li> | |||
<li>[[#Serialize a form with JavaScript]]</li> | |||
<li>[[#Send the form to PHP with AJAX]]</li> | |||
<li>[[#Post the tweet using a PHP Twitter Library]] | |||
</ol> | |||
---- | |||
===Get the JSON with [[PHP]] and [[cURL]]=== | |||
<source lang="PHP" > | |||
<?php | |||
$user = 'username'; | |||
$password = 'password'; | |||
$ch = curl_init("http://api.twitter.com/1/statuses/home_timeline.json?count=3"); | |||
curl_setopt($ch,CURLOPT_TIMEOUT, 30); | |||
curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password); | |||
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); | |||
$result=curl_exec ($ch); | |||
?> | |||
</source> | |||
<p>The ability to use [http://curl.haxx.se/ cURL], is what allows us to interact with Twitter with the command-line, the same commands exist in PHP and we're using them right now to fetch the JSON. | |||
---- | |||
===Print the Tweets=== | |||
<source lang="PHP" highlight="14-20"> | |||
<?php | |||
$user = 'username'; | |||
$password = 'password'; | |||
$ch = curl_init("http://api.twitter.com/1/statuses/home_timeline.json?count=3"); | |||
curl_setopt($ch,CURLOPT_TIMEOUT, 30); | |||
curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password); | |||
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); | |||
$result=curl_exec ($ch); | |||
$resultado = json_decode($result, true); | |||
foreach ($resultado as $value) { | |||
echo $value["user"]["name"]; | |||
echo $value["text"]; | |||
echo $value["created_at"]; | |||
} | |||
?> | |||
</source> | |||
In the hightlighted area we decode the json into an array and then iterate and print the values of that array, with a little bit of CSS we can achieve something like this:</p> | |||
[[File:Screen_shot_2010-07-07_at_7.24.39_PM.png]] | |||
---- | |||
===Serialize a form with [[JavaScript]]=== | |||
<p>This is the part, where i want to show a few more things about JSON which is the JSON Parsers. JSON usually travels between web app and the server as a string, javascript has a really nice (and dangerous!) function which is <em><strong>eval()</strong></em> this function reads string values and interprets it as javascript, which is quite convenient if the JSON file comes from a secure source, however we can't assure the security of an external service like twitter, so i'm going to use a parser to convert the values of our form into a JSON, while i'm also going to show the opposite, convert a JSON into a Javascript Object with the parser</p> | |||
<sub>To save a few lines i'll be using the [http://www.jquery.com jQuery Framework]</sub> | |||
<source lang="javascript"> | |||
<form action="sendTweet.php" method="post" accept-charset="utf-8"> | |||
<input type="text" name="username" value="" id="username"> | |||
<input type="pasword" name="password" value="" id="password"> | |||
<textarea name="tweet" value="tweet"></textarea> | |||
<p><input type="submit" id="submit" value="Continue →"></p> | |||
</form> | |||
<script type="text/javascript" charset="utf-8" src="json2.js"></script> | |||
<script type="text/javascript" charset="utf-8" src="jquery-1.4.2.min.js"></script> | |||
<script type="text/javascript" charset="utf-8"> | |||
$(document).ready(function(){ | |||
$('form').submit(function(e){ | |||
e.preventDefault(); | |||
obj = new Object; //Going to do an object only to use the parser | |||
obj.username = $('#username').val(); | |||
obj.password = $('#password').val() | |||
obj.tweet = $('#tweet').val(); | |||
obj2string = JSON.stringify(obj); //convert object to json string | |||
}); | |||
}); | |||
</script> | |||
</source> | |||
<p>As you can see, i'm using the parser to safely convert a javascript object to a JSON String</p> | |||
---- | |||
===Send the form to PHP with AJAX=== | |||
Here i'm sending the previous JSON string to a PHP file with AJAX, and parsing the twitter answer into a javascript object. To every request, Twitter responds with a JSON, in this case, the JSON file contains the info about the tweet we posted using PHP. | |||
<source lang="javascript"> | |||
$.post("sendTweet.php",{"sendedTweet":obj2string},function(data)){ | |||
tweet = JSON.parse(data); //convert json string to object | |||
} | |||
</source> | |||
---- | |||
===Post the tweet using a [http://dev.twitter.com/pages/libraries PHP Twitter Library]=== | |||
<p>On the other side in PHP, we get the values, and we use a PHP Library to send the tweet, libraries change according to its programmer, so it's always a good idea to read the instructions.</p> | |||
<p>On the other hand, if you don't want to use a library you can always use the cURL method showed above to do an authenticated post</p> | |||
<source lang="php"> | |||
<?php | |||
//Currently using the Tijs Verkoyen library http://classes.verkoyen.eu/twitter/ | |||
if(isset($_POST['sendedTweet'])){ | |||
$tweet = json_decode($_POST['sendedTweet']); #decode the JSON string | |||
$username = $tweet['username']; | |||
$password = $tweet['password']; | |||
$tweet = $tweet['tweet']; | |||
include "twitter_library.php"; | |||
$twi_user = new Twitter("$username","$password"); | |||
$user_text = $tweet; | |||
$twi_user->updateStatus($user_text); | |||
echo $twi_user | |||
} | |||
?> | |||
</source> | |||
<p>And that's pretty much it. I hope i was able to make myself clear during this article, however if you have any doubt please feel free to contact me to [mailto:lcouto87@gmail.com here]</p> | |||
==Resources== | |||
* [http://www.json.org JSON Official Website] | |||
* [http://www.twitter.com Twitter.com] | |||
* [http://dev.twitter.com Twitter Developer Page] | |||
* [http://www.php.net PHP.net] | |||
* [http://www.jquery.com jQuery.com] | |||
--[[User:Couto|Couto]] 21:07, 7 July 2010 (UTC) | |||
[[Category:Javascript]] | |||
[[Category:Netztechnik]] | |||
[[Category:Programmiersprachen]] | |||
[[Category:Software]] | |||
[[Category:Webtechnologien]] | |||
[[Category:Louis Couto]] |