jQuery Widget : We get a lot of request from our users & developer community about ” How to create your own jQuery Widget “. In this jQuery Widget tutorial, we will explain how to create a simple jQuery Widget. We will be using mysql as backend storage and php as a server-side scripting language. We will also use jQuery 1.7.2 to perform our jQuery operations.
What is jQuery Widget?
Sites like Facebook, Twitter, Google+, Linked in & Pinterest provides jquery widgets for other sites. For example facebook like widget, twitter tweet widget, facebook share widget. So those are called jQuery Widgets. From screenshot we can clearly see how all social networking sites uses them in their API and SDK.
As we can see that when we put facebook like button javascript it creates this cool like button on our website. We are creating a simple version of jQuery Widget to illustrate concept behind jQuery Widget. Then you can dive into it for detailed knowledge. Let’s get started.
jQuery Widget Implementation Requirements
- jQuery 1.7.2.
- Basic knowledge of jQuery code.
- Any Server side scripting language although we will use PHP for this tutorial (I will explain code in PHP for server side logic).
Coding jQuery Widget
Introduction: we are creating a jQuery Widget which will output particular product given by server using javascript. So client puts javascript code given by server api on his webpage. when page loads javascript calls server api to retrieve output and that will be added to webpage. pretty simple.
Step 1: Create a Database or use existing database. Execute the following sql query in your database to add post table or you can use your existing table and change code accordingly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
CREATE TABLE `post` ( `id` int(11) NOT NULL AUTO_INCREMENT, `post_title` varchar(200) NOT NULL, `post_content` text NOT NULL, `post_status` enum('publish','draft') NOT NULL, `post_date` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; INSERT INTO `post` (`id`, `post_title`, `post_content`, `post_status`, `post_date`) VALUES (2, 'About CodeRiddles', 'CodeRiddles, A web & Mobile Development tutorials to make your way in IT career', 'publish', '2014-05-19'), (3, 'Lorem Post', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry''s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.', 'publish', '2014-05-25'), (4, 'Kids Zone', 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.', 'publish', '2014-05-25'), (5, 'Member Instruction', 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary.', 'publish', '2014-05-25'), (6, 'Draft Post', 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.', 'draft', '2014-05-25'), (7, 'Evolution', 'Randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary', 'publish', '2014-05-25'), (8, 'Memories', 'You need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.', 'publish', '2014-05-25'), (9, 'What is Lorem Ipsum', 'jQuery Widget Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry''s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.', 'publish', '2014-05-25'), (10, 'Codeigniter', 'CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you''re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you''re tired of ponderously large and thoroughly undocumented frameworks, then CodeIgniter might be a good fit.', 'publish', '2014-05-25'), (11, 'IPLT20', 'Official site provides news, scorecards, videos and pictures. Free live streaming is provided during the matches.', 'publish', '2014-05-25'), (12, 'Bing', 'Bing is a search engine that brings together the best of search and people in your social networks to help you spend less time searching and more time doing.', 'publish', '2014-05-25'), (13, 'Yahoo', 'A new welcome to Yahoo. The new Yahoo experience makes it easier to discover the news and information that you care about most. ', 'publish', '2014-05-25'), (14, 'Turbo Engine', 'A turbocharger, or turbo (colloquialism), from Latin "turbo" ("spinning top"), is a turbine-driven forced induction device that increases an engine''s efficiency', 'publish', '2014-05-25'); |
Step 2: Create a file on your server. We are using PHP so let’s create server.php file. Add following code in server.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php header('Content-type: application/x-javascript'); $str = ""; if(!@$_GET['id']) { $str = '<div style="color:red;">ERROR</div>'; } else { $conn = mysql_connect("localhost","root","root"); if(!$conn) { $str = "Connection Error"; } else { $selected_db = mysql_select_db("ci",$conn); $q = mysql_query("select * from post where id = ".$_GET['id'],$conn); $row = mysql_fetch_array($q); $str = '<div style="background-color:#e8e8e8; width:280px;padding:10px;"><h2>'.$row["post_title"].'</h2><p>'.substr($row["post_content"],0,200).'</p></div>'; } } echo $_GET['callback']."({'html': '".$str."' })"; ?> |
Here we add header line indicating output is javascript. So browser will treat output as a javascript instead of text/html. Next we create $str variable with blank string. Now at server side we are expecting an ID parameter in GET array for which we have to return post details. If we haven’t get any ID then we will simply set $str string to ERROR. If we have an id then we will open mysql connection and retrieve record from post table with same id. Then we set $str variable with HTML containing post title and post content details. Finally, last line which echo function with name whatever we get in $_GET['callback'] which we will see in client side script. and function body to a JSON containing html key with $str as value.
Now let’s move to Client Side Logic of jQuery Widget.
Step 3: Create a file in other website or wherever you want to. I am creating in same directory for demo purpose. I set it’s name to client.html. Add following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<html> <head></head> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <div> <div id="example-widget-container"></div> </div> <script type="text/javascript"> (function () { function e() { t = window.jQuery; t(document).ready(function (e) { var t = "http://localhost:8888/jquery_widget/server.php?id=2&callback=?"; e.getJSON(t).done(function (t) { e("#example-widget-container").html(t.html) }) }) } var t; if (window.jQuery === undefined || window.jQuery.fn.jquery !== "1.7.2") { var n = document.createElement("script"); n.setAttribute("type", "text/javascript"); n.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"); if (n.readyState) { n.onreadystatechange = function () { if (this.readyState == "complete" || this.readyState == "loaded") { scriptLoadHandler() } } } else { n.onload = e }(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(n) } else { e() } })() </script> </body> </html> |
We have a basic HTML structure here containing div element with id example-widget-container. After that we have a block of javascript. In document ready event, we set server side call URL including id & callback as a parameter in URL. id is whatever post we want to retrieve. we can also remove it from here and modify server code to get random post. But callback is required with value set to question mark(?). which will send unique callback string to server. server will return same function. We call server URL using getJSON and when it completed we fetch html key from returned JSON and put it in div element. Rest of the code of javascript block is to ensure proper jQuery is loaded or not. If not, load proper jQuery for our jQuery widget to work properly.
Step 4: Time to run in browser. open client.html in browser. Because it’s HTML file we directly open. as you can see we get what we returned in server side login. Have a look at below output of jQuery Widget we just created from scratch.
What you have to do next is to compact javascript and give it to public so they can show your post on their website. Feel free to customise your jQuery Widget the way you want it to look.
Download code and modify URL as needed.
Please like our Facebook Fan page for instant updates on Tutorials.