<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JQuery &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:23:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>JQuery &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Writing JavaScript Tests Using Jasmine Framework</title>
		<link>https://mail.sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/</link>
					<comments>https://mail.sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 10 Oct 2016 00:00:33 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Jasmine Framework]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Unit Testing With Jasmine]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11903</guid>

					<description><![CDATA[[toc] Introduction In this post we will see how we can write unit test cases in JavaScript. Here we are going to use a framework called Jasmine to write and test our unit test cases. Jasmine is a behavior driven development framework to test our JavaScript codes. The interesting things about Jasmine framework are, it doesn&#8217;t even require a DOM, independent on any framework, clean and easy. Here I will show you how we can create and run our JavaScript tests. I am going to use Visual Studio 2015 for the development. I hope you will like this article. Download [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post we will see how we can write unit test cases in <a href="http://sibeeshpassion.com/category/JavaScript/" target="_blank" rel="noopener">JavaScript</a>. Here we are going to use a framework called Jasmine to write and test our unit test cases. Jasmine is a behavior driven development framework to test our JavaScript codes. The interesting things about Jasmine framework are, it doesn&#8217;t even require a DOM, independent on any framework, clean and easy. Here I will show you how we can create and run our JavaScript tests. I am going to use <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015 for the development. I hope you will like this article.</p>
<h2><strong>Download source code</strong></h2>
<ul>
<li><a href="https://code.msdn.microsoft.com/Writing-JavaScript-Tests-2d1f99e9" target="_blank" rel="noopener">JavaScript Tests With Jasmine</a></li>
</ul>
<h2><strong>Background</strong></h2>
<p>As a developer, we all writes JavaScript codes for our client side developments. Am I right? It is more important to check whether the codes we have written works well. So for that we developer usually do unit testing, few developers are doing a manual testing to just check whether the functionality is working or not. But most of the MNC&#8217;s has set of rules to be followed while developing any functionalities, one of them is writing test cases, once the test cases passes, then only you will be allowed to move your codes to other environments. Here I will show you how we can write client side test cases with the help of a framework called Jasmine.</p>
<h2><strong>Setting up the project</strong></h2>
<p>To get started, please create an empty project in your Visual Studio.</p>
<div id="attachment_11904" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11904" class="size-full wp-image-11904" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png" alt="empty_project" width="650" height="507" srcset="/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png 458w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-300x234.png 300w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-400x312.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11904" class="wp-caption-text">empty_project</p></div>
<p>Now, we will install <a href="http://sibeeshpassion.com/category/jquery/" target="_blank" rel="noopener">jQuery</a>, <a href="http://sibeeshpassion.com/category/jquery-ui/" target="_blank" rel="noopener">jQueryUI </a>from Nuget package manager.</p>
<div id="attachment_11905" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Nuget_Package_Manager.png"><img decoding="async" aria-describedby="caption-attachment-11905" class="size-large wp-image-11905" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Nuget_Package_Manager-1024x478.png" alt="nuget_package_manager" width="634" height="296" srcset="/wp-content/uploads/2016/10/Nuget_Package_Manager-1024x478.png 1024w, /wp-content/uploads/2016/10/Nuget_Package_Manager-300x140.png 300w, /wp-content/uploads/2016/10/Nuget_Package_Manager-768x358.png 768w, /wp-content/uploads/2016/10/Nuget_Package_Manager-400x187.png 400w, /wp-content/uploads/2016/10/Nuget_Package_Manager-1287x600.png 1287w, /wp-content/uploads/2016/10/Nuget_Package_Manager.png 1842w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11905" class="wp-caption-text">nuget_package_manager</p></div>
<p>We are all set to start our coding now.</p>
<h3><strong>Creating page and needed JS file</strong></h3>
<p>Next, we are going to create a page as preceding, with two text boxes and needed references.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;title&gt;Writing JavaScript test cases with Jasmine framework &#8211; Sibeesh Passion&lt;/title&gt;<br />
&lt;meta charset=&#8221;utf-8&#8243; /&gt;<br />
&lt;link href=&#8221;Content/themes/base/jquery-ui.min.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;link href=&#8221;Content/themes/base/base.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;script src=&#8221;Scripts/jquery-3.1.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;Scripts/jquery-ui-1.12.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;Scripts/Index.js&#8221;&gt;&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
Start Date: &lt;input type=&#8221;text&#8221; name=&#8221;name&#8221; value=&#8221;&#8221; id=&#8221;dtStartDate&#8221; /&gt;<br />
End Date: &lt;input type=&#8221;text&#8221; name=&#8221;name&#8221; value=&#8221;&#8221; id=&#8221;dtEndDate&#8221; /&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Now we can start writing our JavaScript codes in the file <em>Index.js</em>. We will start with a document ready function as preceding.</p>
<p>[js]<br />
$(function () {<br />
$(&#8220;#dtStartDate&#8221;).datepicker();<br />
$(&#8220;#dtEndDate&#8221;).datepicker();<br />
$(&#8220;#dtEndDate&#8221;).on(&#8220;change leave&#8221;, function () {<br />
});<br />
});<br />
[/js]</p>
<p>Shall we create our validation functions? We will be creating a namespace indexPage and functions. You can see the validations below.</p>
<p>[js]<br />
var indexPage = {};<br />
indexPage.validationFunctions = (function () {<br />
return {<br />
getStartDateSelectedValue: function () {<br />
return $(&#8220;#dtStartDate&#8221;).val();<br />
},<br />
getEndDateSelectedValue: function () {<br />
return $(&#8220;#dtEndDate&#8221;).val();<br />
},<br />
isNullValue: function (selVal) {<br />
if (selVal.trim() == &#8220;&#8221;) {<br />
return true;<br />
}<br />
else {<br />
return false;<br />
}<br />
},<br />
isNullValueWithUIElements: function () {<br />
if (indexPage.validationFunctions.isNullValue(indexPage.validationFunctions.getStartDateSelectedValue())<br />
&amp;&amp; indexPage.validationFunctions.isNullValue(indexPage.validationFunctions.getEndDateSelectedValue())) {<br />
alert(&#8220;The values can&#8217;t be null!.&#8221;);<br />
}<br />
},<br />
isEndDateGreaterStart: function () {<br />
var startDate = new Date(indexPage.validationFunctions.getStartDateSelectedValue());<br />
var endDate = new Date(indexPage.validationFunctions.getEndDateSelectedValue());<br />
if (startDate &lt; endDate) {<br />
return true;<br />
}<br />
else {<br />
alert(&#8220;End date must be greater than start date!.&#8221;)<br />
return false;<br />
}<br />
}<br />
}<br />
}(jQuery));<br />
[/js]</p>
<p>Hope you are able t understand the codes written. We are wrote some validations like Null value check, end date greater than start date etc&#8230;</p>
<p>Now please run your application and check whether the validations are working fine.</p>
<div id="attachment_11906" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Null_validation_check.png"><img decoding="async" aria-describedby="caption-attachment-11906" class="size-large wp-image-11906" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Null_validation_check-1024x319.png" alt="null_validation_check" width="634" height="198" srcset="/wp-content/uploads/2016/10/Null_validation_check-1024x319.png 1024w, /wp-content/uploads/2016/10/Null_validation_check-300x93.png 300w, /wp-content/uploads/2016/10/Null_validation_check-768x239.png 768w, /wp-content/uploads/2016/10/Null_validation_check-400x124.png 400w, /wp-content/uploads/2016/10/Null_validation_check.png 1231w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11906" class="wp-caption-text">null_validation_check</p></div>
<div id="attachment_11907" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Date_validation_check.png"><img decoding="async" aria-describedby="caption-attachment-11907" class="size-large wp-image-11907" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Date_validation_check-1024x319.png" alt="date_validation_check" width="634" height="198" srcset="/wp-content/uploads/2016/10/Date_validation_check-1024x319.png 1024w, /wp-content/uploads/2016/10/Date_validation_check-300x93.png 300w, /wp-content/uploads/2016/10/Date_validation_check-768x239.png 768w, /wp-content/uploads/2016/10/Date_validation_check-400x125.png 400w, /wp-content/uploads/2016/10/Date_validation_check.png 1223w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11907" class="wp-caption-text">date_validation_check</p></div>
<p>Now, here comes the real part.</p>
<h3><strong>Setting up Jasmine Framework</strong></h3>
<p>To set Jasmine, we will add a new project to our solution.</p>
<div id="attachment_11908" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Add_new_project.png"><img decoding="async" aria-describedby="caption-attachment-11908" class="size-large wp-image-11908" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Add_new_project-1024x709.png" alt="add_new_project" width="634" height="439" srcset="/wp-content/uploads/2016/10/Add_new_project-1024x709.png 1024w, /wp-content/uploads/2016/10/Add_new_project-300x208.png 300w, /wp-content/uploads/2016/10/Add_new_project-768x532.png 768w, /wp-content/uploads/2016/10/Add_new_project-160x110.png 160w, /wp-content/uploads/2016/10/Add_new_project-400x277.png 400w, /wp-content/uploads/2016/10/Add_new_project-866x600.png 866w, /wp-content/uploads/2016/10/Add_new_project.png 1178w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11908" class="wp-caption-text">add_new_project</p></div>
<p>Now install Jasmine from Nuget Package manager.</p>
<div id="attachment_11909" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Nuget_Package.png"><img decoding="async" aria-describedby="caption-attachment-11909" class="size-large wp-image-11909" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Nuget_Package-1024x570.png" alt="jasmine_nuget_package" width="634" height="353" srcset="/wp-content/uploads/2016/10/Jasmine_Nuget_Package-1024x570.png 1024w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-300x167.png 300w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-768x428.png 768w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-400x223.png 400w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-1078x600.png 1078w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package.png 1491w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11909" class="wp-caption-text">jasmine_nuget_package</p></div>
<p>Once you are done, the required files would be added to your project. We will be discussing about Jasmine once everything is set. So no worries.</p>
<p>Now please add a new HTML file on your Jasmine project, this is the page where we can see the test cases in actions, and add all the references as follows.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;</p>
<p>&lt;html lang=&#8221;en&#8221; xmlns=&#8221;http://www.w3.org/1999/xhtml&#8221;&gt;<br />
&lt;head&gt;<br />
&lt;meta charset=&#8221;utf-8&#8243; /&gt;<br />
&lt;title&gt;Jasmine Spec Runner &#8211; Sibeesh Passion&lt;/title&gt;<br />
&lt;link href=&#8221;content/jasmine/jasmine.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;script src=&#8221;http://localhost:12387/Scripts/jquery-3.1.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;http://localhost:12387/Scripts/jquery-ui-1.12.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/jasmine.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/jasmine-html.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/console.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/boot.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/indextests.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;http://localhost:12387/Scripts/Index.js&#8221;&gt;&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;</p>
<p>&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<blockquote><p>Please do not forget to include the js files where we actually written the validations, jquery, jqueryui (if needed). Here indextests.js is the file where we are going to write the test cases.</p></blockquote>
<p>Normally this page is called as Spec Runner, Now you may be thinking what is a Spec? Before going further, there are some terms you must be aware of, there are listed below.</p>
<ul>
<li>Suites</li>
</ul>
<p>A suit is the starting point of a Jasmine test cases, it actually calls the global jasmine function <em>describe</em>. It can have two parameters, a string value which describes the suit, and a function which implements the suit.</p>
<ul>
<li>Spec</li>
</ul>
<p>Like suites, a spec starts with a string which can be the title of the suit and a function where we write the tests. A spec can contain one or more expectation that test the state of our code.</p>
<ul>
<li>Expectation</li>
</ul>
<p>Value of an expectation is either true or false, an expectation starts with the function <em>expect</em>. It takes a value and call the actual one.</p>
<p>You can always read more <a href="http://jasmine.github.io/2.0/introduction.html" target="_blank" rel="noopener">here</a>. Now please run your SpecRunner.html page. If everything is fine you can see a page as below.</p>
<div id="attachment_11910" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page.png"><img decoding="async" aria-describedby="caption-attachment-11910" class="size-large wp-image-11910" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-1024x223.png" alt="jasmine_spec_runner_page" width="634" height="138" srcset="/wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-1024x223.png 1024w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-300x65.png 300w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-768x167.png 768w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-400x87.png 400w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11910" class="wp-caption-text">jasmine_spec_runner_page</p></div>
<p>So are you all set? Shall we go and write our test cases? Please go to your <em>IndexTest.js</em> file and create a suit and spec as preceding.</p>
<p>[js]<br />
describe(&#8220;Includes validations for index page&#8221;, function () {<br />
var indexPage;<br />
beforeEach(function () {<br />
indexPage = window.indexPage.validationFunctions;<br />
});</p>
<p>it(&#8220;Check for null values&#8221;, function () {<br />
// We are going to pass &#8220;&#8221; (null) value to the function<br />
var retVal = indexPage.isNullValue(&#8220;&#8221;);<br />
expect(retVal).toBeTruthy();<br />
});</p>
<p>});<br />
[/js]</p>
<p>Here the expectation is true and we give toBeTruthy(), now lets go and find whether the test is passed or not. Please run the SpecRunner.html page again.</p>
<div id="attachment_11911" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Test_Jasmine_Specs.png"><img decoding="async" aria-describedby="caption-attachment-11911" class="size-large wp-image-11911" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Test_Jasmine_Specs-1024x199.png" alt="test_jasmine_specs" width="634" height="123" srcset="/wp-content/uploads/2016/10/Test_Jasmine_Specs-1024x199.png 1024w, /wp-content/uploads/2016/10/Test_Jasmine_Specs-300x58.png 300w, /wp-content/uploads/2016/10/Test_Jasmine_Specs-768x149.png 768w, /wp-content/uploads/2016/10/Test_Jasmine_Specs-400x78.png 400w, /wp-content/uploads/2016/10/Test_Jasmine_Specs.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11911" class="wp-caption-text">test_jasmine_specs</p></div>
<p>Now we will write test case for our function <em>isEndDateGreaterStart</em>, if you have noticed the function <em>isEndDateGreaterStart</em>, you can see that there are dependencies (UI elements). Inside of the function, we are getting the values from the UI elements.</p>
<p>[js]<br />
var startDate = new Date(indexPage.validationFunctions.getStartDateSelectedValue());<br />
var endDate = new Date(indexPage.validationFunctions.getEndDateSelectedValue());<br />
[/js]</p>
<p>So in this case, we need to mock this values. It is known as &#8216;Spy&#8217; in Jasmine. We can use a function called <em>SpyOn</em> for this.</p>
<p>[js]<br />
it(&#8220;Spy call for datepicker date validation&#8221;, function () {<br />
//Start date as 2015-03-25<br />
spyOn(indexPage, &#8220;getStartDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-25&#8221;);<br />
//End date as 2015-03-24<br />
spyOn(indexPage, &#8220;getEndDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-24&#8221;);<br />
var retVal = indexPage.isEndDateGreaterStart();<br />
expect(retVal).toBeFalsy();<br />
});<br />
[/js]</p>
<p>Here we are giving start date as 2015-03-25 and end date as 2015-03-24 and we know 2015-03-25 &lt; 2015-03-24 is false, so here we are giving expectation as false (toBeFalsy()). Now you are getting an alert as follows right?</p>
<div id="attachment_11912" style="width: 776px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278.png"><img decoding="async" aria-describedby="caption-attachment-11912" class="size-full wp-image-11912" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278.png" alt="alert_in_spyon_jasmine" width="766" height="571" srcset="/wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278.png 478w, /wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278-300x224.png 300w, /wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278-650x485.png 650w, /wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278-400x298.png 400w" sizes="(max-width: 766px) 100vw, 766px" /></a><p id="caption-attachment-11912" class="wp-caption-text">alert_in_spyon_jasmine</p></div>
<p>But in testing framework we don&#8217;t need any alerts right? To get rid of this, you must create a spy for window.alert function and add it to the <em>beforeEach</em> so that it can be used for each specs. You can do that as follows.</p>
<p>[js]<br />
window.alert = jasmine.createSpy(&#8220;alert&#8221;).and.callFake(function () { });<br />
[/js]</p>
<p>Once after you add this code, alert message won&#8217;t be thrown. Now please add an another spec with true values (Start date &#8211; 2015-03-25, End date &#8211; 2015-03-26), so that it will return true.</p>
<p>[js]<br />
it(&#8220;Spy call for datepicker date validation toBeTruthy&#8221;, function () {<br />
//Start date as 2015-03-25<br />
spyOn(indexPage, &#8220;getStartDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-25&#8221;);<br />
//End date as 2015-03-26<br />
spyOn(indexPage, &#8220;getEndDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-26&#8221;);<br />
var retVal = indexPage.isEndDateGreaterStart();<br />
expect(retVal).toBeTruthy();<br />
});<br />
[/js]</p>
<p>Now you can see all of your specs are passed.</p>
<div id="attachment_11913" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Run_all_specs_in_Jasmine.png"><img decoding="async" aria-describedby="caption-attachment-11913" class="size-large wp-image-11913" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-1024x217.png" alt="run_all_specs_in_jasmine" width="634" height="134" srcset="/wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-1024x217.png 1024w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-300x64.png 300w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-768x163.png 768w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-400x85.png 400w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11913" class="wp-caption-text">run_all_specs_in_jasmine</p></div>
<p>Happy coding!.</p>
<h2><strong>Conclusion</strong></h2>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Upload Images To Azure Media Service From Client Side</title>
		<link>https://mail.sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/</link>
					<comments>https://mail.sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 30 Jun 2016 00:00:31 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Client Side Uploading Using SAS In Azure]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Media service account]]></category>
		<category><![CDATA[SAS in Azure]]></category>
		<category><![CDATA[Upload images to Azure]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11734</guid>

					<description><![CDATA[In this article we are going to see how we can upload images or any files to Media Service Account in Azure. If you are new to Azure media service account, I strongly recommend you to read my previous post related to media service account. Once we create a media service account, we will create an asset and get the SAS token related to the asset we created, we will discuss more about asset and SAS token. I hope you will like this. Download the source code You can always download the source code here: Azure Media Service From Client [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we are going to see how we can upload images or any files to Media Service Account in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure</a>. If you are new to Azure media service account, I strongly recommend you to read my previous post related to <a href="http://sibeeshpassion.com/working-with-azure-media-service-account/" target="_blank">media service account</a>. Once we create a media service account, we will create an asset and get the SAS token related to the asset we created, we will discuss more about asset and SAS token. I hope you will like this.</p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Upload-To-Azure-Media-fd2c0449" target="_blank">Azure Media Service From Client Side</a></p>
<p><strong>Background</strong></p>
<p>For the past few weeks I am working in <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure </a>. Recently I got a requirement of storing images to Azure. Thus I decided to create a media service account for this requirement. The tricky part was I needed to upload the files from client side itself. Here we are going to see how we can create an Azure media service account and how to use the same. </p>
<p><strong>What is media service account?</strong></p>
<li>A media service account is a Azure based account which gives you access to cloud based media services in Azure.</li>
<li>Stores metadata of the media files you create, instead saving the actual media content.</li>
<li>To work with media service account, you must have an associated storage account.</li>
<li>While creating a media service account, you can either select the storage account you already have or you can create a new one.</li>
<li>Since the media service account and storage account is treated separately, the content will be available in your storage account even if you delete your media service account</li>
<blockquote><p>
Please be noted that your storage account region must be same as your media service account region.
</p></blockquote>
<p><strong>Prerequisites</strong></p>
<li>Visual Studio</li>
<li>Azure account with active subscription</li>
<p>If you are a start up company or you are in thinking to start a one, you can always go for BizSpark(Software and services made for the start ups), to join please check here: <a href="http://sibeeshpassion.com/how-to-join-bizspark/" target="_blank">How to join bizspark</a>. Or you can always create a free account <a href="https://azure.microsoft.com/en-in/pricing/free-trial/" target="_blank">here</a>.</p>
<p><strong>Things we are going to do</strong></p>
<p>The following are the tasks we are going to do.</p>
<li>Creating an Azure media service account.</li>
<p>If you don&#8217;t have an Azure account with active subscription, you must creates it first before going to do this task.</p>
<li>Create an Asset in Media service account</li>
<li>Get the SAS token for an Asset</li>
<li>Client side upload process</li>
<li>Retrieves the uploaded items</li>
<p>Now we will go and create our media service account.</p>
<p><strong>Create an Azure media service account</strong></p>
<p>To create an azure media service account, please see the link given below. I have explained the steps there.</p>
<li><a href="http://sibeeshpassion.com/working-with-azure-media-service-account/" target="_blank">Working With Azure Media Service Account</a></li>
<p>Hope you have got the storage account and media service account with you.</p>
<p><strong>Create an Asset in Media service account</strong></p>
<p>You can always create an Asset either via code or manually in <em>https://portal.azure.com</em>.</p>
<div id="attachment_11736" style="width: 596px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Blob-Service-In-Portal.png"><img decoding="async" aria-describedby="caption-attachment-11736" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Blob-Service-In-Portal.png" alt="Blob Service In Portal" width="586" height="134" class="size-full wp-image-11736" srcset="/wp-content/uploads/2016/06/Blob-Service-In-Portal.png 586w, /wp-content/uploads/2016/06/Blob-Service-In-Portal-300x69.png 300w, /wp-content/uploads/2016/06/Blob-Service-In-Portal-400x91.png 400w" sizes="(max-width: 586px) 100vw, 586px" /></a><p id="caption-attachment-11736" class="wp-caption-text">Blob Service In Portal</p></div>
<div id="attachment_11737" style="width: 328px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/New-Container.png"><img decoding="async" aria-describedby="caption-attachment-11737" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/New-Container.png" alt="New Container" width="318" height="308" class="size-full wp-image-11737" srcset="/wp-content/uploads/2016/06/New-Container.png 318w, /wp-content/uploads/2016/06/New-Container-300x291.png 300w" sizes="(max-width: 318px) 100vw, 318px" /></a><p id="caption-attachment-11737" class="wp-caption-text">New Container</p></div>
<p>If you want to create the Asset via code, you can create as below. </p>
<p>[csharp]<br />
public static string CreateBLOBContainer(string containerName)<br />
        {<br />
            try<br />
            {<br />
                string result = string.Empty;<br />
                CloudMediaContext mediaContext;<br />
                mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);<br />
                IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);<br />
                return asset.Uri.ToString();<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                return ex.Message;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>You can always get the sample codes for creating the assets from here: <a href="https://code.msdn.microsoft.com/Working-With-Azure-Media-ad283589#content" target="_blank">Azure Media Service Account</a></p>
<p><strong>Get the SAS token for an Asset</strong></p>
<p>Before going to generate SAS, we want to know what is a SAS right?</p>
<p><strong>What is SAS?</strong></p>
<p>SAS stands for shared access signature, it is the mechanism used for giving limited access to the objects in your storage account to your clients, in the way that you do not need to share your account key. In SAS, you can set how long the given access must be active and you can always set the read/write access too. If you want to know more about the SAS, I recommend you to read <a href="https://azure.microsoft.com/en-in/documentation/articles/storage-dotnet-shared-access-signature-part-1/" target="_blank">here</a>. </p>
<p>Once you downloaded the application from <a href="https://code.msdn.microsoft.com/Working-With-Azure-Media-ad283589" target="_blank">here</a>, you can add a function to generate the SAS token dynamically</p>
<p>[csharp]<br />
 private static string GenerateSASToken(string assetId)<br />
        {<br />
            CloudStorageAccount backupStorageAccount = CloudStorageAccount.Parse(myAzureCon);<br />
            CloudBlobClient client = backupStorageAccount.CreateCloudBlobClient();<br />
            CloudBlobContainer container = client.GetContainerReference(assetId);<br />
            BlobContainerPermissions permissions = container.GetPermissions();</p>
<p>            permissions.SharedAccessPolicies.Add(string.Concat(assetId, &quot;AccessPolicy&quot;), new SharedAccessBlobPolicy<br />
            {<br />
                Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,<br />
                SharedAccessExpiryTime = DateTime.UtcNow.AddDays(365)<br />
            });<br />
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;<br />
            container.SetPermissions(permissions);</p>
<p>            ServiceProperties sp = client.GetServiceProperties();<br />
            sp.DefaultServiceVersion = &quot;2013-08-15&quot;;<br />
            CorsRule cr = new CorsRule(); cr.AllowedHeaders.Add(&quot;*&quot;);<br />
            cr.AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Put | CorsHttpMethods.Post;<br />
            cr.AllowedOrigins.Add(&quot;*&quot;);<br />
            cr.ExposedHeaders.Add(&quot;x-ms-*&quot;);<br />
            sp.Cors.CorsRules.Clear();<br />
            sp.Cors.CorsRules.Add(cr);<br />
            client.SetServiceProperties(sp);<br />
            var sas = container.GetSharedAccessSignature(new SharedAccessBlobPolicy(), string.Concat(assetId, &quot;AccessPolicy&quot;));<br />
            return container.Uri + sas;<br />
        }<br />
[/csharp]</p>
<p>Here we are giving the asset id of the asset we just created. And the function will give you the SAS token we need. Hope you understood. Now we can start our client side coding for uploading.</p>
<p><strong>Client side upload process</strong></p>
<p>Create an index page with an input file and other needed UI as follows.</p>
<p>[html]<br />
&lt;!doctype html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;meta charset=&quot;utf-8&quot;&gt;<br />
    &lt;meta name=&quot;viewport&quot; content=&quot;user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width&quot;&gt;<br />
    &lt;link href=&quot;CSS/Index.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;div class=&quot;container&quot;&gt;<br />
        &lt;div class=&quot;thumbnail-fit&quot; id=&quot;azureImage&quot;&gt;<br />
            &lt;div id=&quot;fiesInfo&quot;&gt;&lt;/div&gt;<br />
            &lt;div id=&quot;divOutput&quot;&gt;&lt;/div&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
    &lt;div id=&quot;uploaderDiv&quot;&gt;<br />
        &lt;form&gt;<br />
            &lt;span class=&quot;input-control text&quot;&gt;<br />
                &lt;input type=&quot;file&quot; id=&quot;file&quot; multiple accept=&quot;image/*&quot; name=&quot;file&quot; /&gt;<br />
            &lt;/span&gt;<br />
            &lt;br /&gt;<br />
            &lt;br /&gt;<br />
            &lt;input type=&quot;button&quot; value=&quot;Upload File&quot; id=&quot;buttonUploadFile&quot; /&gt;<br />
        &lt;/form&gt;<br />
    &lt;/div&gt;<br />
    &lt;script src=&quot;scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;scripts/jquery-ui-1.9.2.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;scripts/Index.js&quot;&gt;&lt;/script&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Now create a JS file <em>Index.js</em>. And create a file change function as follows. Sounds good?</p>
<p>[js]<br />
$(document).ready(function () {<br />
    $(&#8216;#fiesInfo&#8217;).html(&#8221;);<br />
    $(&#8216;#divOutput&#8217;).html(&#8221;);<br />
    upldCount = 0;<br />
    totSize = 0;</p>
<p>    $(&#8216;#file&#8217;).change(function () {<br />
        selectedFile = [];<br />
        if (this.files.length &gt; 0) {<br />
            $.each(this.files, function (i, v) {<br />
                totalFileSize = totalFileSize + v.size;<br />
                selectedFile.push({ size: v.size, name: v.name, file: v });<br />
            });<br />
        }<br />
    });<br />
});<br />
[/js]</p>
<p>Here we are pushing the selected files to an array in a needed format. Now we will add the upload click event.</p>
<p>[js]</p>
<p>$(&quot;#buttonUploadFile&quot;).click(function (e) {<br />
    upload();<br />
});<br />
[/js]</p>
<p>And following is the code for the function <em>upload</em>.</p>
<p>[js]<br />
function upload() {<br />
    $(&#8216;#fiesInfo&#8217;).html(&#8221;);<br />
    $(&#8216;#divOutput&#8217;).html(&#8221;);<br />
    upldCount = 0;<br />
    totSize = 0;<br />
    startDateTime = new Date();<br />
    $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;span&gt;&lt;b&gt; Uploading starts at &lt;/b&gt;&lt;/span&gt;&#8217; + startDateTime);<br />
    if (selectedFile == null) {<br />
        alert(&quot;Please select a file first.&quot;);<br />
    }<br />
    else {<br />
        for (var i = 0; i &lt; selectedFile.length; i++) {<br />
            fileUploader(selectedFile[i]);<br />
            upldCount = upldCount + 1;;<br />
            totSize = totSize + selectedFile[i].size;<br />
        }<br />
    }<br />
};<br />
[/js]</p>
<p>Did you notice that we are calling a function inside a loop which accepts file content as parameter?</p>
<p>[js]<br />
function fileUploader(selectedFileContent) {<br />
    reader = new FileReader();<br />
    var fileContent = selectedFileContent.file.slice(0, selectedFileContent.size &#8211; 1);<br />
    reader.readAsArrayBuffer(fileContent);<br />
    reader.onloadend = function (evt) {<br />
        if (evt.target.readyState == FileReader.DONE) {<br />
            var currentAzureStorageUrl = baseUrl;<br />
            var indexOfQueryStart = currentAzureStorageUrl.indexOf(&quot;?&quot;);<br />
            var uuid = generateUUID();<br />
            var fileExtension = selectedFileContent.name.split(&#8216;.&#8217;).pop();<br />
            var azureFileName = uuid + &#8216;.&#8217; + fileExtension;<br />
            submitUri = currentAzureStorageUrl.substring(0, indexOfQueryStart) + &#8216;/&#8217; + azureFileName + currentAzureStorageUrl.substring(indexOfQueryStart);<br />
            var requestData = new Uint8Array(evt.target.result);<br />
            ajaxUploadCall(submitUri, requestData);<br />
        }<br />
    };<br />
}<br />
[/js]</p>
<blockquote><p>
Here <em>baseUrl</em> is the SAS you just created for an asset. The example of SAS is <em>https://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sv=2015-04-05&#038;st=2015-04-29T22%3A18%3A26Z&#038;se=2015-04-30T02%3A23%3A26Z&#038;sr=b&#038;sp=rw&#038;sip=168.1.5.60-168.1.5.70&#038;spr=https&#038;sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D</em></p></blockquote>
<p>Once the reader onloadend event is finished we are passing the uri and data in the format of array. Can we see the AJAX call now?</p>
<p>[js]<br />
function ajaxUploadCall(submitUri, selectedFileContent) {<br />
    $.ajax({<br />
        url: submitUri,<br />
        type: &quot;PUT&quot;,<br />
        data: selectedFileContent,<br />
        processData: false,<br />
        async: false,<br />
        beforeSend: function (xhr) {<br />
            xhr.setRequestHeader(&#8216;x-ms-blob-type&#8217;, &#8216;BlockBlob&#8217;);<br />
        },<br />
        success: function (data, status) {</p>
<p>        },<br />
        complete: function (event, xhr, settings) {<br />
            compCount = compCount + 1;<br />
            if (selectedFile.length == compCount) {<br />
                RptDisplay();<br />
            }<br />
        },<br />
        error: function (xhr, desc, err) {<br />
        }<br />
    });<br />
}<br />
[/js]</p>
<p>In your ajax call please do not forget to add the header as below. </p>
<p>[js]<br />
 beforeSend: function (xhr) {<br />
            xhr.setRequestHeader(&#8216;x-ms-blob-type&#8217;, &#8216;BlockBlob&#8217;);<br />
        }<br />
[/js]</p>
<p>If every selected files are uploaded we are calling a function <em>RptDisplay()</em> right?</p>
<p>[js]<br />
function RptDisplay() {<br />
    $(&#8216;#divOutput&#8217;).hide();<br />
    $(&#8216;#fiesInfo&#8217;).append(&#8216;&lt;table&gt;&lt;/table&gt;&#8217;);<br />
    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;No of files uploaded: &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + upldCount + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Total size uploaded: &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + formatSizeUnits(totSize) + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
    var endDateTime = new Date();<br />
    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;Uploading ends at &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + endDateTime + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
    $(&#8216;#fiesInfo table&#8217;).append(&#8216;&lt;tr&gt;&lt;td&gt;&lt;b&gt;The time taken is &lt;/b&gt;&lt;/td&gt;&lt;td&gt;&#8217; + findDateDiff(startDateTime, endDateTime) + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;);<br />
    $(&#8216;#divOutput&#8217;).show();<br />
};<br />
[/js]</p>
<p>You can get all the other needed functions like findDateDiff(), formatSizeUnits(), generateUUID() and the CSS from the source code attached. Please download the same. Now please run your page and you can find an input file there, select few files and try upload, if you have configured everything fine, I am sure you will get a report. Let us see that now. </p>
<div id="attachment_11738" style="width: 266px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File.png"><img decoding="async" aria-describedby="caption-attachment-11738" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File.png" alt="Upload File" width="256" height="130" class="size-full wp-image-11738" /></a><p id="caption-attachment-11738" class="wp-caption-text">Upload File</p></div>
<div id="attachment_11739" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png"><img decoding="async" aria-describedby="caption-attachment-11739" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png" alt="Upload File Output" width="650" height="215" class="size-full wp-image-11739" srcset="/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png 650w, /wp-content/uploads/2016/06/Upload-File-Output-e1467268304577-300x99.png 300w, /wp-content/uploads/2016/06/Upload-File-Output-e1467268304577-400x132.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11739" class="wp-caption-text">Upload File Output</p></div>
<p><strong>Retrieves the uploaded items</strong></p>
<p>To retrieve the items you can always create a function as follows, which accepts asset id as parameter. </p>
<p>[csharp]<br />
public string getEventImage(string assetID)<br />
        {<br />
            CloudStorageAccount backupStorageAccount = CloudStorageAccount.Parse(myAzureCon);<br />
            CloudBlobClient client = backupStorageAccount.CreateCloudBlobClient();<br />
            CloudBlobContainer container = client.GetContainerReference(assetID.Replace(&quot;nb:cid:UUID:&quot;, &quot;asset-&quot;));<br />
            List&lt;string&gt; results = new List&lt;string&gt;();<br />
            foreach (IListBlobItem item in container.ListBlobs(null, false))<br />
            {<br />
                results.Add(item.Uri.ToString());<br />
            }<br />
            return JsonConvert.SerializeObject(results);<br />
        }<br />
[/csharp]</p>
<p>Now if you login to your azure portal and click on the asset you created, you can see the contents are uploaded there.</p>
<div id="attachment_11742" style="width: 599px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/06/Uploaded-Contents.png"><img decoding="async" aria-describedby="caption-attachment-11742" src="http://sibeeshpassion.com/wp-content/uploads/2016/06/Uploaded-Contents.png" alt="Uploaded Contents" width="589" height="315" class="size-full wp-image-11742" srcset="/wp-content/uploads/2016/06/Uploaded-Contents.png 589w, /wp-content/uploads/2016/06/Uploaded-Contents-300x160.png 300w, /wp-content/uploads/2016/06/Uploaded-Contents-400x214.png 400w" sizes="(max-width: 589px) 100vw, 589px" /></a><p id="caption-attachment-11742" class="wp-caption-text">Uploaded Contents</p></div>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever tried Azure media service account? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/upload-images-to-azure-media-service-from-client-side/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Style Or Format JSON Data In JQuery</title>
		<link>https://mail.sibeeshpassion.com/style-or-format-json-data-in-jquery/</link>
					<comments>https://mail.sibeeshpassion.com/style-or-format-json-data-in-jquery/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 31 May 2016 00:00:34 +0000</pubDate>
				<category><![CDATA[How to]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Format JSON]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[JSON in Pre Tag]]></category>
		<category><![CDATA[Style JSON Data]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11648</guid>

					<description><![CDATA[In this post we will discuss how we can format or style the JSON you get from the server. Sometimes you may need to show the exact JSON you get from your API or from server in your web page. Normally if you just bind this JSON to any pre tag, it will look like just a straight line. Isn&#8217;t it? To overcome this we have an option in jQuery . I hope you will like this. Background For the past few months I am working with some Web API projects. As you all know the preferred output of an [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will discuss how we can format or style the <a href="http://sibeeshpassion.com/tag/json/" target="_blank">JSON </a>you get from the server. Sometimes you may need to show the exact JSON you get from your API or from server in your web page. Normally if you just bind this JSON to any pre tag, it will look like just a straight line. Isn&#8217;t it? To overcome this we have an option in <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank">jQuery </a>. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>For the past few months I am working with some <a href="http://sibeeshpassion.com/category/web-api/" target="_blank">Web API</a> projects. As you all know the preferred output of an API is JSON, I am returning JSON from my API. I wanted to show this JSON in a Pre tag as a result, but in a formatted way or stylish way. Here I am going to explain how we can do this. </p>
<p><strong>Using the code</strong></p>
<p>Before getting started, please make sure that you have added the jQuery reference to your page.</p>
<p>[html]<br />
 &lt;script src=&quot;scripts/jquery-2.2.3.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Now let us say we are getting a JSON as follows from our API.</p>
<p>[js]<br />
[{&quot;AreaCode&quot;:&quot;B697-31&quot;,&quot;Revenue&quot;:12747128.190000001},{&quot;AreaCode&quot;:&quot;B697-92&quot;,&quot;Revenue&quot;:7922559.1600000048},{&quot;AreaCode&quot;:&quot;B697-76&quot;,&quot;Revenue&quot;:7541039.540000001},{&quot;AreaCode&quot;:&quot;B697-46&quot;,&quot;Revenue&quot;:7076495.5800000066},{&quot;AreaCode&quot;:&quot;B553-131&quot;,&quot;Revenue&quot;:5738816.5099999979},{&quot;AreaCode&quot;:&quot;B553-193&quot;,&quot;Revenue&quot;:4608556.52},{&quot;AreaCode&quot;:&quot;B697-74&quot;,&quot;Revenue&quot;:3895194.1099999994},{&quot;AreaCode&quot;:&quot;D158-233&quot;,&quot;Revenue&quot;:3572808.989999996},{&quot;AreaCode&quot;:&quot;B697-78&quot;,&quot;Revenue&quot;:3512657.6999999937},{&quot;AreaCode&quot;:&quot;B672-31&quot;,&quot;Revenue&quot;:2955916.9800000032},{&quot;AreaCode&quot;:&quot;B553-46&quot;,&quot;Revenue&quot;:2806813.7100000042}]<br />
[/js]</p>
<p>It will obviously looks like preceding when you just append it to a pre tag.</p>
<div id="attachment_11650" style="width: 526px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag.png"><img decoding="async" aria-describedby="caption-attachment-11650" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag.png" alt="JSON in Pre Tag" width="516" height="115" class="size-full wp-image-11650" srcset="/wp-content/uploads/2016/05/JSON-in-Pre-Tag.png 516w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-300x67.png 300w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-400x89.png 400w" sizes="(max-width: 516px) 100vw, 516px" /></a><p id="caption-attachment-11650" class="wp-caption-text">JSON in Pre Tag</p></div>
<p>Now we will format this JSON string with JQuery Parse and JQuery stringify method as follows. </p>
<p>[js]<br />
  var tmpData = JSON.parse(data);<br />
                    var formattedData = JSON.stringify(tmpData, null, &#8216;\t&#8217;);<br />
                    $(&#8216;#output&#8217;).text(formattedData);<br />
[/js]</p>
<p>Here output is the id of our pre tag which we defined as follows.</p>
<p>[html]<br />
&lt;pre id=&quot;output&quot;&gt;&lt;/pre&gt;<br />
[/html]</p>
<p>Now if you bind the data after the formatting to pre tag, you will get an out put as follows. </p>
<div id="attachment_11651" style="width: 526px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output.png"><img decoding="async" aria-describedby="caption-attachment-11651" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output.png" alt="JSON in Pre Tag Output" width="516" height="861" class="size-full wp-image-11651" srcset="/wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output.png 516w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output-180x300.png 180w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output-400x667.png 400w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output-360x600.png 360w" sizes="(max-width: 516px) 100vw, 516px" /></a><p id="caption-attachment-11651" class="wp-caption-text">JSON in Pre Tag Output</p></div>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/style-or-format-json-data-in-jquery/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>TagIt Control With Data From Database Using Angular JS In MVC Web API</title>
		<link>https://mail.sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/</link>
					<comments>https://mail.sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:46 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[TagIt]]></category>
		<category><![CDATA[TagIt Tags From Database]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11245</guid>

					<description><![CDATA[In this article we will learn how to load the tags from database in MVC Web API using Angular JS. Here we are going to use a pretty control called tagIt which does the tag part easier with a lot of configuration options. This article use a normal MVC application which includes the Web API control in it, in addition to it, we uses Angular JS for our client side operations. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. AngularJS Tips, Tricks, Blogs MVC Tips, Tricks, Blogs Web API Tips, Tricks, Blogs As [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how to load the tags from database in MVC Web API using Angular JS. Here we are going to use a pretty control called tagIt which does the tag part easier with a lot of configuration options. This article use a normal MVC application which includes the Web API control in it, in addition to it, we uses Angular JS for our client side operations. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. </p>
<li><a href="http://sibeeshpassion.com/category/angularjs/" target="_blank" rel="noopener">AngularJS Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>As the article title implies, we are actually going to load the tags from a table called tblTags from <a href="http://sibeeshpassion.com/category/SQL/" target="_blank" rel="noopener">SQL </a>Server database.  So now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/TagIt-Control-With-Data-aa3371f7" target="_blank" rel="noopener">Load Tags From Database Using Angular JS In MVC Web API</a></p>
<p><strong>Background</strong></p>
<p>Few days back I was trying to use the tagIt widget in one of my application. I could do that with some pre defined tags as a variable. Then I thought why don&#8217;t we try some thing like loading these tags from database. Hence my application uses MVC architecture, I selected Web API for retrieving the data from database. I hope someone can find this useful.</p>
<p><strong>Create a MVC application</strong></p>
<p>Click File-> New-> Project then select MVC application.  Before going to start the coding part, make sure that all the required extensions/references are installed. Below are the required things to start with. </p>
<li>Angular JS</li>
<li>TagIt Plugin</li>
<li>jQuery</li>
<p>You can all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.</p>
<div id="attachment_11235" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" aria-describedby="caption-attachment-11235" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" width="650" height="432" class="size-full wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11235" class="wp-caption-text">Manage NuGet Package Window</p></div>
<p>Once you have installed those items, please make sure that all the items(jQuery, Angular JS files, Tag It JS files like tag-it.js) are loaded in your scripts folder. </p>
<p><strong>Using the code</strong></p>
<p>Before going to load the tags from a database we will try to load our tagit control with some predefined array values. No worries, later we will change this array values to the values we get from database. </p>
<p><em>Include the references in your _Layout.cshtml</em></p>
<p>As we have already installed all the packages we need, now we need to add the references, right?</p>
<p>[html]<br />
@RenderBody()</p>
<p>    @Scripts.Render(&quot;~/bundles/jquery&quot;)<br />
    &lt;script src=&quot;~/Scripts/jquery-2.2.0.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Content/jquery-ui.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/angular.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/angular-route.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/tag-it.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/MyScripts/TagScripts.js&quot;&gt;&lt;/script&gt;<br />
    @RenderSection(&quot;scripts&quot;, required: false)<br />
[/html]</p>
<p>Here <em>TagScripts.js</em> is the JavaScript file where we are going to write our own scripts.  </p>
<p><em>Set the changes in View</em></p>
<p>So we have added the references, now we will make the changes in our view. As we uses Angular JS, we will set our ng-app and ng-controller as follows. </p>
<p>[html]<br />
&lt;div ng-app=&quot;tagApp&quot;&gt;<br />
    &lt;div ng-controller=&quot;tagController&quot;&gt;<br />
        &lt;ul id=&quot;tags&quot;&gt;&lt;/ul&gt;<br />
        &lt;div id=&quot;error&quot;&gt;Nothing found!&lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>You can give a style as follows if you want.</p>
<p>[css]<br />
&lt;style&gt;<br />
    #tags {<br />
        width: 25%;<br />
    }</p>
<p>    #error {<br />
        display:none;<br />
        font-weight: bold;<br />
        color: #1c94c4;<br />
        font-family: Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;<br />
        font-size: 1.1em;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p>Oops!, I forgot to mention, please do not forget to include the CSS style sheets. </p>
<p>[html]<br />
&lt;link href=&quot;~/Content/jquery-ui.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;link href=&quot;~/Content/jquery.tagit.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
[/html]</p>
<p>Now we can write the scripts in our TagScripts.js file. </p>
<p><em>Create Angular App</em></p>
<p>You can create an Angular module as follows. </p>
<p>[js]<br />
var app;<br />
    //Angular App<br />
    app = angular.module(&#8216;tagApp&#8217;, []);<br />
[/js]</p>
<blockquote><p>Here the module name must be same as we have given in ng-app in our view. </p></blockquote>
<p><em>Create Angular Controller</em></p>
<p>You can create an Angular Controller as follows. </p>
<p>[js]<br />
app.controller(&#8216;tagController&#8217;, function ($scope) {<br />
        $(&quot;#tags&quot;).tagit({<br />
            availableTags: availableTags,<br />
            autocomplete: { delay: 0, minLength: 1 },<br />
            beforeTagAdded: function (event, ui) {<br />
                if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                    $(&#8216;#error&#8217;).show();<br />
                    return false;<br />
                } else {<br />
                    $(&#8216;#error&#8217;).hide();<br />
                }<br />
            }<br />
        });<br />
    });<br />
[/js]</p>
<p>As you can see we have called tagit() function to initialize the tagit control. Below are the explanations to the options we have given.</p>
<li>availableTags</li>
<p>availableTags are the source we need to apply to the control so that the given items can be shown on user actions. </p>
<li>autocomplelte</i>
<p>autocomplete is a property which enables the auto complete option, when it is true user will get the items listed accordingly for each key press</p>
<li>beforeTagAdded</li>
<p>beforeTagAdded is a callback function which gets fired before we add the new tags to the control. This function can be used to do all the needed tasks before adding the given item to the control. For example, if we need to load only the values from the database and if we need to restrict creating the new tags by the user, means user will be allowed to use only the available tags which is in the available tag array. The preceding code block does what has been explained above.</p>
<p>[js]<br />
if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                    $(&#8216;#error&#8217;).show();<br />
                    return false;<br />
                } else {<br />
                    $(&#8216;#error&#8217;).hide();<br />
                }<br />
[/js]</p>
<p>If user tries to add a new tag, we will show the alert div which we already set in our view.</p>
<p>Now it is time to see the control in our view, let us see whether it works fine, if not, we may need to go back and checks again.  </p>
<div id="attachment_11260" style="width: 562px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array.png"><img decoding="async" aria-describedby="caption-attachment-11260" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array.png" alt="Tag_It_Control_Defined_Array" width="552" height="169" class="size-full wp-image-11260" srcset="/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array.png 552w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array-300x92.png 300w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array-400x122.png 400w" sizes="(max-width: 552px) 100vw, 552px" /></a><p id="caption-attachment-11260" class="wp-caption-text">Tag_It_Control_Defined_Array</p></div>
<div id="attachment_11261" style="width: 557px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found.png"><img decoding="async" aria-describedby="caption-attachment-11261" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found.png" alt="Tag_It_Control_Defined_Array_If_Nothing_Found" width="547" height="135" class="size-full wp-image-11261" srcset="/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found.png 547w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found-300x74.png 300w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found-400x99.png 400w" sizes="(max-width: 547px) 100vw, 547px" /></a><p id="caption-attachment-11261" class="wp-caption-text">Tag_It_Control_Defined_Array_If_Nothing_Found</p></div>
<p>It seems everything is fine, thank god we don&#8217;t need any debugging 🙂</p>
<p>Now we will create a Web API controller. Oh yeah, we are going to start our real coding. Right click on your controller folder and click new.</p>
<div id="attachment_11238" style="width: 614px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web_API_controller.png"><img decoding="async" aria-describedby="caption-attachment-11238" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web_API_controller.png" alt="Web_API_controller" width="604" height="396" class="size-full wp-image-11238" srcset="/wp-content/uploads/2016/02/Web_API_controller.png 604w, /wp-content/uploads/2016/02/Web_API_controller-300x197.png 300w, /wp-content/uploads/2016/02/Web_API_controller-400x262.png 400w" sizes="(max-width: 604px) 100vw, 604px" /></a><p id="caption-attachment-11238" class="wp-caption-text">Web_API_controller</p></div>
<p>So our Web API controller is ready, then it is time to go to do some Angular JS scripts, don&#8217;t worry we will come back here. </p>
<p>We need to make changes to our Angular JS controller <em>tagController </em> as follows. </p>
<p>[js]<br />
    //Angular Controller<br />
    app.controller(&#8216;tagController&#8217;, function ($scope, tagService) {<br />
        //Angular service call<br />
        var tgs = tagService.getTags();<br />
        if (tgs != undefined) {<br />
            tgs.then(function (d) {<br />
                availableTags = [];<br />
                for (var i = 0; i &lt; d.data.length; i++) {<br />
                    availableTags.push(d.data[i].tagName);<br />
                }</p>
<p>                $(&quot;#tags&quot;).tagit({<br />
                    availableTags: availableTags,<br />
                    autocomplete: { delay: 0, minLength: 1 },<br />
                    beforeTagAdded: function (event, ui) {<br />
                        if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                            $(&#8216;#error&#8217;).show();<br />
                            return false;<br />
                        } else {<br />
                            $(&#8216;#error&#8217;).hide();<br />
                        }<br />
                    }<br />
                });<br />
                console.log(JSON.stringify(availableTags));<br />
            }, function (error) {<br />
                console.log(&#8216;Oops! Something went wrong while fetching the data.&#8217;);<br />
            });<br />
        }<br />
    });<br />
[/js]</p>
<p>As you have noticed, we are calling an Angular JS service here. Once we get the data from the service, we are assigning it to the array which we have initialized with the predefined values, so that the data from the database will be available in the tagit control. So can we create our Angular JS service?</p>
<p>[js]<br />
    //Angular Service<br />
    app.service(&#8216;tagService&#8217;, function ($http) {<br />
        //call the web api controller<br />
        this.getTags = function () {<br />
            return $http({<br />
                method: &#8216;get&#8217;,<br />
                url: &#8216;api/tag&#8217;<br />
            });<br />
        }<br />
    });<br />
[/js]</p>
<p>This will fire our Web API controller and action GET api/tag. And the Web API controller will give you the results which we will format again and give to the available tag array. Sounds cool? Wait, we can do all these stuffs without Angular JS, means we can simply call a jQuery Ajax Get. Do you want to see how? Here it is. </p>
<p>[js]<br />
/* Using jQuery */</p>
<p>$(function () {<br />
    var availableTags = [<br />
      &quot;ActionScript&quot;,<br />
      &quot;AppleScript&quot;,<br />
      &quot;Asp&quot;,<br />
      &quot;BASIC&quot;,<br />
      &quot;C&quot;,<br />
      &quot;C++&quot;,<br />
      &quot;Clojure&quot;,<br />
      &quot;COBOL&quot;,<br />
      &quot;ColdFusion&quot;,<br />
      &quot;Erlang&quot;,<br />
      &quot;Fortran&quot;,<br />
      &quot;Groovy&quot;,<br />
      &quot;Haskell&quot;,<br />
      &quot;Java&quot;,<br />
      &quot;JavaScript&quot;,<br />
      &quot;Lisp&quot;,<br />
      &quot;Perl&quot;,<br />
      &quot;PHP&quot;,<br />
      &quot;Python&quot;,<br />
      &quot;Ruby&quot;,<br />
      &quot;Scala&quot;,<br />
      &quot;Scheme&quot;<br />
    ];<br />
    //Load the available tags from database start<br />
    $.ajax({<br />
        type: &#8216;GET&#8217;,<br />
        dataType: &#8216;json&#8217;,<br />
        contentType: &#8216;application/json;charset=utf-8&#8217;,<br />
        url: &#8216;http://localhost:56076/api/Tag&#8217;,<br />
        success: function (data) {<br />
            try {<br />
                if (data.length &gt; 0) {<br />
                    availableTags = data;<br />
                }<br />
            } catch (e) {<br />
                console.log(&#8216;Error while formatting the data : &#8216; + e.message)<br />
            }<br />
        },<br />
        error: function (xhrequest, error, thrownError) {<br />
            console.log(&#8216;Error while ajax call: &#8216; + error)<br />
        }<br />
    });<br />
    //Load the available tags from database end</p>
<p>    $(&quot;#tags&quot;).tagit({<br />
        availableTags: availableTags,<br />
        autocomplete: { delay: 0, minLength: 1 },<br />
        beforeTagAdded: function (event, ui) {<br />
            if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                $(&#8216;#error&#8217;).show();<br />
                return false;<br />
            } else {<br />
                $(&#8216;#error&#8217;).hide();<br />
            }<br />
        }<br />
    });<br />
});<br />
[/js]</p>
<p>Now only thing pending is to get the data from our API controller, we will see that part now. For that first you must create a database and a table in it right?</p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]    Script Date: 17-Feb-16 10:21:17 PM ******/<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create a table 🙂</p>
<p><strong>Create table in database</strong></p>
<p>Below is the query to create table in database.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[tblTags]    Script Date: 17-Feb-16 10:22:00 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[tblTags](<br />
	[tagId] [int] IDENTITY(1,1) NOT NULL,<br />
	[tagName] [nvarchar](50) NOT NULL,<br />
	[tagDescription] [nvarchar](max) NULL,<br />
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED<br />
(<br />
	[tagId] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the table now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[tblTags]<br />
           ([tagName]<br />
           ,[tagDescription])<br />
     VALUES<br />
           (&lt;tagName, nvarchar(50),&gt;<br />
           ,&lt;tagDescription, nvarchar(max),&gt;)<br />
GO<br />
[/sql]</p>
<p>So let us say, we have inserted the data as follows.</p>
<div id="attachment_11248" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631.png"><img decoding="async" aria-describedby="caption-attachment-11248" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631.png" alt="Insertion_In_Table" width="650" height="176" class="size-full wp-image-11248" srcset="/wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631.png 650w, /wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631-300x81.png 300w, /wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631-400x108.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11248" class="wp-caption-text">Insertion_In_Table</p></div>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder. </p>
<div id="attachment_11249" style="width: 339px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/ADO_NET_Model_Entity.png"><img decoding="async" aria-describedby="caption-attachment-11249" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/ADO_NET_Model_Entity.png" alt="ADO_NET_Model_Entity" width="329" height="207" class="size-full wp-image-11249" srcset="/wp-content/uploads/2016/02/ADO_NET_Model_Entity.png 329w, /wp-content/uploads/2016/02/ADO_NET_Model_Entity-300x189.png 300w" sizes="(max-width: 329px) 100vw, 329px" /></a><p id="caption-attachment-11249" class="wp-caption-text">ADO_NET_Model_Entity</p></div>
<p>Then it is time to go back our Web API controller. Please change the code as below.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web;<br />
using System.Web.Http;<br />
using Load_Tags_From_DB_Using_Angular_JS_In_MVC.Models;</p>
<p>namespace Load_Tags_From_DB_Using_Angular_JS_In_MVC.Controllers<br />
{<br />
    public class TagController : ApiController<br />
    {<br />
        private DBEntities db = new DBEntities();</p>
<p>        // GET api/Tag<br />
        public IEnumerable&lt;tblTag&gt; Get()<br />
        {<br />
            return db.tblTags.AsEnumerable();<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Once this is done, we can say that we are finished with all steps. That&#8217;s fantastic right? Now we will see the output.</p>
<p><strong>Output</strong></p>
<div id="attachment_11250" style="width: 563px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Load_Tags_From_Database_Output.png"><img decoding="async" aria-describedby="caption-attachment-11250" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Load_Tags_From_Database_Output.png" alt="Load_Tags_From_Database_Output" width="553" height="146" class="size-full wp-image-11250" srcset="/wp-content/uploads/2016/02/Load_Tags_From_Database_Output.png 553w, /wp-content/uploads/2016/02/Load_Tags_From_Database_Output-300x79.png 300w, /wp-content/uploads/2016/02/Load_Tags_From_Database_Output-400x106.png 400w" sizes="(max-width: 553px) 100vw, 553px" /></a><p id="caption-attachment-11250" class="wp-caption-text">Load_Tags_From_Database_Output</p></div>
<p>Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Did you try Web API yet? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>jQuery Datatable With Server Side Data</title>
		<link>https://mail.sibeeshpassion.com/jquery-datatable-with-server-side-data-2/</link>
					<comments>https://mail.sibeeshpassion.com/jquery-datatable-with-server-side-data-2/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:43 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Datatable With Server Side]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[jQuery Datatables]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11266</guid>

					<description><![CDATA[Introduction In this article, we will learn how we can work with jQuery Datatables with server-side data. Here we are going to use an MVC application with jQuery and other required packages installed in it. If you are new to MVC, You can always get the tips/tricks/blogs about that here MVC Tips, Tricks, Blogs. jQuery Datatables is a client-side grid control that is lightweight and easy to use. But when it comes to grid control, it must be usable when it supports the server-side loading of data. This control is perfect for that. I guess, it is enough for the [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>In this article, we will learn how we can work with jQuery Datatables with server-side data. Here we are going to use an MVC application with jQuery and other required packages installed in it. If you are new to MVC, You can always get the tips/tricks/blogs about that here MVC Tips, Tricks, Blogs. jQuery Datatables is a client-side grid control that is lightweight and easy to use. But when it comes to grid control, it must be usable when it supports the server-side loading of data. This control is perfect for that. I guess, it is enough for the introduction. Now we will start using our grid. I hope you will like this.</p>



<h2 class="wp-block-heading"><strong>Download the source code</strong></h2>



<p>You can always download the source code here:</p>



<ul class="wp-block-list"><li><a href="https://github.com/SibeeshVenu/jQuery-Datatable-With-Server-Side-Data" target="_blank" rel="noreferrer noopener">Datatable With Server-Side Data</a></li></ul>



<h2 class="wp-block-heading"><strong>Create a MVC application</strong></h2>



<p>Click File-&gt; New-&gt; Project then select MVC application. Before going to start the coding part, make sure that all the required extensions/references are installed. Below are the required things to start with.</p>



<ul class="wp-block-list"><li>Datatables Package</li><li>jQuery</li></ul>



<p>You can all the items mentioned above from NuGet. Right-click on your project name and select Manage NuGet packages.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" width="650" height="432" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" class="wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Manage NuGet Package Window</figcaption></figure>



<p>Once you have installed those items, please make sure that all the items(jQuery, Datatables JS files) are loaded in your scripts folder.</p>



<h2 class="wp-block-heading"><strong>Using the code</strong></h2>



<p>Now let us add the needed references.</p>



<h3 class="wp-block-heading">Include the references in your _Layout.cshtml</h3>



<p>As we have already installed all the packages we need, now we need to add the references, right? After adding the reference, your _Layout.cshtml will looks like below.</p>



<script src="https://gist.github.com/SibeeshVenu/4b71315abf732ca3a929e8750cf13638.js"></script>



<p>Here <em>MyScripts.js</em> is the JavaScript file where we are going to write our own scripts.</p>



<p><em>Add a normal MVC controller</em></p>



<p>Now we will add a normal MVC controller in our app. Once you add that you can see an ActionResult is created for us.</p>



<p><code>public ActionResult Index()<br>{<br>return View();<br>}</code></p>



<p>Right-click on the controller, and click add view, that will create a View for you. Now we will change the view as follows. </p>



<script src="https://gist.github.com/SibeeshVenu/87fa8feefb4bd7fcb9fbc867d8a23921.js"></script>



<p>So we have set the headers and footer for our grid, where we are going to load the grid control in the table <em>myGrid</em>. So far the UI part is done, now it is time to set up our database and entity model. Are you ready?</p>



<h3 class="wp-block-heading"><strong>Create a database</strong></h3>



<p>The following query can be used to create a database in your SQL Server.</p>



<script src="https://gist.github.com/SibeeshVenu/5bf2b19e004f619ebfb1f9e6229ef66b.js"></script>



<p>Now we will create a table 🙂</p>



<h3 class="wp-block-heading"><strong>Create table in database</strong></h3>



<p>Below is the query to create table in database.</p>



<script src="https://gist.github.com/SibeeshVenu/8b4797ecfbcfe5841f9ca85a5ef131c8.js"></script>



<h3 class="wp-block-heading"><strong>Insert data to table</strong></h3>



<p>To insert the data, I will attach a database script file along with the download file, you can either run that or insert some data by using the below query. By the way, if you would like to know how to generate scripts with data in SQL Server, you can check <a rel="noopener noreferrer" href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank">here</a>.</p>



<script src="https://gist.github.com/SibeeshVenu/9ad0fcd0e2220a4b2a93d7617716416a.js"></script>



<p>Along with this, we can create a new stored procedure that will fetch the data. Following is the query to create the stored procedure.</p>



<script src="https://gist.github.com/SibeeshVenu/40e2e26f6dd93dbac671fc9c33743ccd.js"></script>



<p>Next thing we are going to do is creating a ADO.NET Entity Data Model.</p>



<h3 class="wp-block-heading"><strong>Create Entity Data Model</strong></h3>



<p>Right-click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder.</p>



<p>Now we will go back to our controller and add a new JsonResult which can be called via a new jQuery Ajax request. No worries, we will create that Ajax requests later. Once you add the Jsonresult action, I hope your controller will look like this.</p>



<script src="https://gist.github.com/SibeeshVenu/344693e90203b925d34b755e83a2ec8a.js"></script>



<p>Here <em>TrialsDBEntities </em>is our entity class. Please be noted that to use the model classes in your controller, you must add the reference as follows.</p>



<p><code>using jQuery_Datatable_With_Server_Side_Data.Models;</code></p>



<p>I know all you are familiar with this, I am just saying!. Now can we create a function <em>GetSales</em> in our model class <em>Sales </em>?.</p>



<script src="https://gist.github.com/SibeeshVenu/b7b4a55890e969fe518cd30cd24433fb.js"></script>



<p>We uses normal LINQ queries here, and we take only 100 records to load for now. If you don&#8217;t want to use this method you can call our stored procedure which we have created while creating our database. You can call this as explained in the below function.</p>



<script src="https://gist.github.com/SibeeshVenu/f189bb513e93566d140429b4a9836834.js"></script>



<p>Now the only thing pending is to call our controller JsonResult action right? We will do some code in our MyScript.js file.</p>



<script src="https://gist.github.com/SibeeshVenu/5093c34f6a455a758426ac8df2b00118.js"></script>



<p>Here <em>&#8220;dataSrc&#8221;: &#8220;&#8221; </em> should be used if you have a plain <a rel="noopener noreferrer" href="http://sibeeshpassion.com/tag/json/" target="_blank">JSON </a>data. The sample data can be find below.</p>



<script src="https://gist.github.com/SibeeshVenu/a2ae9ec5f56a05ef62f6f911e4918ba3.js"></script>



<p>We have done everything!. Can we see the output now?</p>



<h2 class="wp-block-heading"><strong>Output</strong></h2>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data.png"><img decoding="async" width="1024" height="596" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1024x596.png" alt="jQuery Datatable With Server Side Data" class="wp-image-11267" srcset="/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1024x596.png 1024w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-300x175.png 300w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-768x447.png 768w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-400x233.png 400w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1030x600.png 1030w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data.png 1097w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption>jQuery Datatable With Server Side Data</figcaption></figure>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search.png"><img decoding="async" width="1024" height="379" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-1024x379.png" alt="jQuery Datatable With Server Side Data Search" class="wp-image-11268" srcset="/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-1024x379.png 1024w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-300x111.png 300w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-768x284.png 768w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-400x148.png 400w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search.png 1109w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption>jQuery Datatable With Server Side Data Search</figcaption></figure>



<p>Have a happy coding.</p>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p>Did I miss anything that you may think which is needed? Did you use jQuery Datatables in your application? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>



<h2 class="wp-block-heading"><strong>Your turn. What do you think?</strong></h2>



<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/jquery-datatable-with-server-side-data-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Change Page Layout Dynamically Using jQuery Layout Plug in</title>
		<link>https://mail.sibeeshpassion.com/change-page-layout-dynamically-using-jquery-layout-plug-in/</link>
					<comments>https://mail.sibeeshpassion.com/change-page-layout-dynamically-using-jquery-layout-plug-in/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 22 Feb 2016 09:32:31 +0000</pubDate>
				<category><![CDATA[How to]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[jQuery Plugin]]></category>
		<category><![CDATA[Page Layout]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11287</guid>

					<description><![CDATA[In this post we are going to see how we can change the layout a page dynamically, with out writing any CSS styles for the page. Sounds cool right? Are you afraid of writing the CSS styles which will suit for all the screens like Mobiles, Tabs, Monitors, High resolution? As I am not a good designer, I was worried all the time about the resolution issues whenever I use any custom styles. Here we will be using a jQuery plugin called jQuery Layout and we do have options to set our Footer, Side bar, Header and many more. Personally [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we are going to see how we can change the layout a page dynamically, with out writing any CSS styles for the page. Sounds cool right? Are you afraid of writing the <a href="http://sibeeshpassion.com/category/CSS/" target="_blank">CSS </a>styles which will suit for all the screens like Mobiles, Tabs, Monitors, High resolution? As I am not a good designer, I was worried all the time about the resolution issues whenever I use any custom styles. Here we will be using a <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank">jQuery </a>plugin called jQuery Layout and we do have options to set our Footer, Side bar, Header and many more. Personally I liked this plug in , That is why I am sharing some information about this plugin. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: 	</p>
<li><a href="http://sibeeshpassion.com/Download/Change_Page_Layout_Dynamically_Using_jQuery_Layout_Plug_in.rar" target="_blank">Change Page Layout Dynamically </a></li>
<p><strong>Background</strong></p>
<p>I came to know about this plugin when I was searching for some page layout for my application. Then I just installed it and started using. It is pretty simple to use. You can always download the files from the plug in page <a href="http://plugins.jquery.com/layout/" target="_blank">here</a>. </p>
<p><strong>Using the code</strong></p>
<p>To start with this plug in, the first thing you are required to do is adding the necessary references. We are going to use three references, jQuery, jquery.layout-latest.js, layout-default-latest.css.</p>
<p>[html]<br />
  &lt;link href=&quot;layout-default-latest.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
    &lt;script src=&quot;jquery-2.2.0.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;jquery.layout-latest.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>The next thing we need is some div elements, we can set it as follows. </p>
<p>[html]<br />
&lt;div class=&quot;ui-layout-center&quot;&gt;Content area&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-north&quot;&gt;Header&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-south&quot;&gt;Footer&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-east&quot;&gt;Sidebar&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-west&quot;&gt;Sidebar&lt;/div&gt;<br />
[/html]</p>
<p>Now we will add the scripts.</p>
<p>[js]<br />
&lt;script&gt;<br />
        $(function () {<br />
            $(&quot;body&quot;).layout({<br />
                applyDefaultStyles:true<br />
            });<br />
        });<br />
    &lt;/script&gt;<br />
[/js]</p>
<p>Here we uses <em>applyDefaultStyles:true</em>, this is for ensuring all the required default conditions/options are being applied automatically. Now if you run your page you will be seeing a layout as follows. </p>
<p><div id="attachment_11288" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Change-Page-Layout-Dynamically.png"><img decoding="async" aria-describedby="caption-attachment-11288" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-1024x484.png" alt="Change Page Layout Dynamically" width="634" height="300" class="size-large wp-image-11288" srcset="/wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-1024x484.png 1024w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-300x142.png 300w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-768x363.png 768w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-400x189.png 400w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-1270x600.png 1270w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically.png 1357w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11288" class="wp-caption-text">Change Page Layout Dynamically</p></div></p>
<p>And this is how your page will look like when you toggle every panes. </p>
<p><div id="attachment_11289" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling-.png"><img decoding="async" aria-describedby="caption-attachment-11289" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling--1024x478.png" alt="Change Page Layout Dynamically WHen Toggling" width="634" height="296" class="size-large wp-image-11289" srcset="/wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling--1024x478.png 1024w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling--300x140.png 300w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling--768x358.png 768w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling--400x187.png 400w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling--1287x600.png 1287w, /wp-content/uploads/2016/02/Change-Page-Layout-Dynamically-WHen-Toggling-.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11289" class="wp-caption-text">Change Page Layout Dynamically WHen Toggling</p></div></p>
<p>Following are the key features offered by the development team as they have mentioned in their plug in home page <a href="http://layout.jquery-dev.com/index.cfm" target="_blank">here</a>.</p>
<li>simple to use: powerful but simple syntax is easy to learn</li>
<li>unlimited layout capabilities: 5 regions per layout &#8211; unlimited nesting</li>
<li>dozens of options: every aspect is customizable, globally and by region</li>
<li>total CSS control: dozens of auto-generated classes create ANY UI look</li>
<li>extensible: callbacks, methods, and special utilities provide total control</li>
<li>custom buttons: integrates with your own buttons for a custom UI look</li>
<li>collapsable: each pane can be closed, using any UI animation you want</li>
<li>hidable: panes can be completely hidden, either on startup or at any time</li>
<li>resizable: each pane can be resized, within automatic or specified limits</li>
<li>slidable: panes can also &#8216;slide open&#8217; for temporary access</li>
<li>headers &#038; footers: each region has unlimited headers or footers</li>
<li>hotkeys: can use the cursor-keys and/or define custom hotkeys</li>
<li>use any elements: use divs, iframes or any elements you want as a &#8216;pane&#8217;</li>
<li>compatible with UI widgets: integrates with jQuery widgets and plug-ins</li>
<li>demo mode: set applyDefaultStyles option for a fully functional layout</li>
<p>The developers have provided so many demo of how we can use this plugin, you can always check those <a href="http://layout.jquery-dev.com/demos.cfm" target="_blank">here</a>.</p>
<p>That is all, now you can start using this plugin. See the complete code below.</p>
<p><strong>Complete code</strong></p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;Change Page Layout Dynamically Using jQuery Layout Plug in&lt;/title&gt;<br />
    &lt;meta charset=&quot;utf-8&quot; /&gt;<br />
    &lt;link href=&quot;layout-default-latest.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
    &lt;script src=&quot;jquery-2.2.0.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;jquery.layout-latest.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script&gt;<br />
        $(function () {<br />
            $(&quot;body&quot;).layout({<br />
                applyDefaultStyles:true<br />
            });<br />
        });<br />
    &lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;div class=&quot;ui-layout-center&quot;&gt;Content area&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-north&quot;&gt;Header&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-south&quot;&gt;Footer&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-east&quot;&gt;Sidebar&lt;/div&gt;<br />
    &lt;div class=&quot;ui-layout-west&quot;&gt;Sidebar&lt;/div&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/change-page-layout-dynamically-using-jquery-layout-plug-in/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Disable Dates In Datepicker</title>
		<link>https://mail.sibeeshpassion.com/disable-dates-in-datepicker/</link>
					<comments>https://mail.sibeeshpassion.com/disable-dates-in-datepicker/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 12 Nov 2015 06:28:23 +0000</pubDate>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[jQuery UI]]></category>
		<category><![CDATA[Datepicker]]></category>
		<category><![CDATA[Disable Dates]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10962</guid>

					<description><![CDATA[In this post we will see how we can disable some dates in a jQuery datepicker control. We all worked in datepicker controls right? But in some situations we may need to add some validations like to restrict some dates in the picker so that user can not select those and move further. Here we are going to disable all the future Saturdays. I hope you will like this. Using the code The first thing you need to do is including the needed files. jQuery jQuery UI jQuery UI CSS Once you are done adding the files, you need to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can disable some dates in a <a href="http://sibeeshpassion.com/category/jquery" target="_blank">jQuery </a>datepicker control. We all worked in datepicker controls right? But in some situations we may need to add some validations like to restrict some dates in the picker so that user can not select those and move further. Here we are going to disable all the future Saturdays. I hope you will like this. </p>
<p><strong>Using the code</strong></p>
<p>The first thing you need to do is including the needed files. </p>
<p><a href="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" target="_blank">jQuery</a></p>
<p><a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" target="_blank">jQuery UI</a></p>
<p><a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/redmond/jquery-ui.css" target="_blank">jQuery UI CSS</a></p>
<p>Once you are done adding the files, you need to add a text box in which we are going to implement the picker. </p>
<p>[html]<br />
&lt;input type=&quot;text&quot; value=&quot;Select Date Here&quot;/&gt;<br />
[/html]</p>
<p>Now we will create an array which contains the list of dates we need to disable.</p>
<p>[js]<br />
var disabledDates = [&quot;2015-11-28&quot;,&quot;2015-11-14&quot;,&quot;2015-11-21&quot;]<br />
[/js]</p>
<p>Next we will load the datepicker to our text box.</p>
<p>[js]<br />
$(&#8216;input&#8217;).datepicker({<br />
    beforeShowDay: function(date){<br />
        var string = jQuery.datepicker.formatDate(&#8216;yy-mm-dd&#8217;, date);<br />
        return [ disabledDates.indexOf(string) == -1 ]<br />
    }<br />
});<br />
[/js]</p>
<p>Have you noticed that we are calling a function beforeShowDay, this is used to disable the dates. It will return false if the date exists in the disabledDates.</p>
<p>That&#8217;s all we have done it. </p>
<p>Please see the jsfiddle here: <a href="http://jsfiddle.net/sibeeshvenu/gj90f1bm/" target="_blank">Disable Date In DatePicker</a></p>
<p><strong>Output</strong></p>
<p><div id="attachment_10964" style="width: 333px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Disable_Dates_in_Datepicker.png"><img decoding="async" aria-describedby="caption-attachment-10964" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Disable_Dates_in_Datepicker.png" alt="Disable Dates In Datepicker" width="323" height="278" class="size-full wp-image-10964" srcset="/wp-content/uploads/2015/11/Disable_Dates_in_Datepicker.png 323w, /wp-content/uploads/2015/11/Disable_Dates_in_Datepicker-300x258.png 300w" sizes="(max-width: 323px) 100vw, 323px" /></a><p id="caption-attachment-10964" class="wp-caption-text">Disable Dates In Datepicker</p></div></p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/disable-dates-in-datepicker/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Hoisting In JavaScript</title>
		<link>https://mail.sibeeshpassion.com/hoisting-in-javascript/</link>
					<comments>https://mail.sibeeshpassion.com/hoisting-in-javascript/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 06 Nov 2015 12:19:21 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Hoisting]]></category>
		<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10955</guid>

					<description><![CDATA[In this post we will discuss the importance and limitations of Hoisting in JavaScript. We all writes client side codes. Right? But few of you might not be aware of the term Hoisting. Hoisting is one of the default behaviour of JavaScript, it is the process of moving all the declarations of the variables to the top of the current function or scope. In this post we will explain this Hoisting in detail with some examples. I hope you will like this. Background I used to spend more time with the client side codes rather than server side codes. In [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will discuss the importance and limitations of Hoisting in <a href="http://sibeeshpassion.com/category/javascript/" target="_blank">JavaScript</a>. We all writes client side codes. Right? But few of you might not be aware of the term Hoisting. Hoisting is one of the default behaviour of JavaScript, it is the process of moving all the declarations of the variables to the top of the current function or scope. In this post we will explain this Hoisting in detail with some examples. I hope you will like this. </p>
<p><strong>Background</strong></p>
<p>I used to spend more time with the client side codes rather than server side codes. In my thought is is always good if you do the formation of your data in client side instead doing it in the server side. Client side loops are always faster than the server side ones. As a client side code developer, you must understand the word Hoisting in JavaScript. Here we will discuss that.</p>
<p><strong>Using the code</strong></p>
<p>Before going through we need to know some facts in JavaScript. </p>
<p><em>Do you know?</em></p>
<p>In JavaScript we can use any variable before it is declared or a variable can be declared after it is used. </p>
<p>For Example: </p>
<p>The below two scripts will return same output.</p>
<p>[js]<br />
&lt;script&gt;<br />
x = 5;<br />
alert(x);<br />
var x;<br />
&lt;/script&gt;<br />
[/js]</p>
<p>And </p>
<p>[js]<br />
&lt;script&gt;<br />
var x;<br />
x = 5;<br />
alert(x);<br />
&lt;/script&gt;<br />
[/js]</p>
<p><strong>Limitations of Hoisting</strong></p>
<p>Even though the process of Hosting will move the declarations to the top, there is some limitations too. We will discuss it here now.</p>
<blockquote><p>Initializing a variable can not be Hoisted or In simple JavaScript Hoists declarations not initializations. </p></blockquote>
<p>For Example:</p>
<p>The below scripts will give different outputs.</p>
<p>[js]<br />
&lt;script&gt;<br />
var x = 2;<br />
var y = 4;<br />
alert(x+y);<br />
&lt;/script&gt;<br />
[/js]</p>
<p>This will give you an output of 6.</p>
<p>And </p>
<p>[js]<br />
&lt;script&gt;<br />
var x = 2;<br />
alert(x+y);<br />
var y = 4;<br />
&lt;/script&gt;<br />
[/js]</p>
<p>This will give you an output of NaN. Since we are initializing the value of y, the JavaScript Hoisting is not happening, so the y value will be undefined. The JavaScript will consider that y is not yet declared. </p>
<p>So the second example is same as of below.</p>
<p>[js]<br />
&lt;script&gt;<br />
var x = 2;<br />
var y;<br />
alert(x+y);<br />
y = 4;<br />
&lt;/script&gt;<br />
[/js]</p>
<p>This will give you an output of NaN.</p>
<p><div id="attachment_10956" style="width: 403px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Hoisting-In-JavaScript.png"><img decoding="async" aria-describedby="caption-attachment-10956" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Hoisting-In-JavaScript.png" alt="Hoisting In JavaScript" width="393" height="207" class="size-full wp-image-10956" srcset="/wp-content/uploads/2015/11/Hoisting-In-JavaScript.png 393w, /wp-content/uploads/2015/11/Hoisting-In-JavaScript-300x158.png 300w" sizes="(max-width: 393px) 100vw, 393px" /></a><p id="caption-attachment-10956" class="wp-caption-text">Hoisting In JavaScript</p></div></p>
<p><strong>Conclusion</strong></p>
<p>Since we are all developers, it is always makes things simple. So much complexity in software comes from trying to make one thing do two things. So always declare your variables on top of your function or scope. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/hoisting-in-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Regex to remove a word from a string</title>
		<link>https://mail.sibeeshpassion.com/regex-to-remove-a-word-from-a-string/</link>
					<comments>https://mail.sibeeshpassion.com/regex-to-remove-a-word-from-a-string/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 02 Nov 2015 10:13:52 +0000</pubDate>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Find a word from a string]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jquery regex]]></category>
		<category><![CDATA[Regex to remove a word from a string]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10890</guid>

					<description><![CDATA[In this post we will see how we can remove a particular word from a string entirely in jQuery. [js] var newString= oldString.replace(/Unspecified/g, &#8221;); [/js] Here I am removing the word Unspecified from my variable oldString. Please see my other posts related to JQuery here: JQuery Posts Kindest Regards Sibeesh Venu]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can remove a particular word from a string entirely in <a href="http://sibeeshpassion.com/category/jquery" target="_blank">jQuery</a>. </p>
<p>[js]<br />
var newString= oldString.replace(/Unspecified/g, &#8221;);<br />
[/js]</p>
<p>Here I am removing the word Unspecified from my variable oldString. </p>
<p>Please see my other posts related to JQuery here: <a href="http://sibeeshpassion.com/tag/jquery/" target="_blank">JQuery Posts</a></p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/regex-to-remove-a-word-from-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Custom Pager Using prev and next In jQuery</title>
		<link>https://mail.sibeeshpassion.com/custom-pager-using-prev-and-next-in-jquery/</link>
					<comments>https://mail.sibeeshpassion.com/custom-pager-using-prev-and-next-in-jquery/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 21 Oct 2015 10:44:24 +0000</pubDate>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[CSS3]]></category>
		<category><![CDATA[Custom Pager]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Next jQuery]]></category>
		<category><![CDATA[Prev jQuery]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10829</guid>

					<description><![CDATA[In this post we will create a custom pager using prev and next functions in jQuery. You can treat this post as a simple demo of using prev and next functions. We will be using some html UI elements and we will apply the paging functionality by using native jQuery codes. In this way you can get the information about on which page is requested by the user, once you get it, you can create an jQuery ajax call and fetch the data from the database and show. You need to know the basic of jQuery and CSS before going [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will create a custom pager using <em>prev </em>and <em>next </em> functions in <a href="http://sibeeshpassion.com/category/jquery" target="_blank">jQuery</a>. You can treat this post as a simple demo of using <em>prev </em>and <em>next </em> functions. We will be using some html UI elements and we will apply the paging functionality by using native jQuery codes. In this way you can get the information about on which page is requested by the user, once you get it, you can create an jQuery ajax call and fetch the data from the database and show. You need to know the basic of jQuery and CSS before going further. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>We can find so many pager in on-line. Here in this post I am just trying to populate my own pager. Please be noted that this is just a demo, so that you can not find more functionalities here. </p>
<p><strong>Using the code</strong></p>
<p>First thing you need to do is create a page.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;Prev Next In jQuery &#8211; Sibeesh Passion&lt;/title&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
   &lt;div id=&quot;container&quot;&gt;<br />
        &lt;div id=&quot;outer&quot;&gt;<br />
            &lt;div&gt;-6&lt;/div&gt;<br />
            &lt;div&gt;-5&lt;/div&gt;<br />
            &lt;div&gt;-4&lt;/div&gt;<br />
            &lt;div&gt;-3&lt;/div&gt;<br />
            &lt;div&gt;-2&lt;/div&gt;<br />
            &lt;div&gt;-1&lt;/div&gt;<br />
            &lt;div class=&quot;first&quot;&gt;0&lt;/div&gt;<br />
            &lt;div&gt;1&lt;/div&gt;<br />
            &lt;div&gt;2&lt;/div&gt;<br />
            &lt;div&gt;3&lt;/div&gt;<br />
            &lt;div&gt;4&lt;/div&gt;<br />
            &lt;div&gt;5&lt;/div&gt;<br />
            &lt;div&gt;6&lt;/div&gt;<br />
            &lt;div&gt;7&lt;/div&gt;<br />
        &lt;/div&gt;<br />
        &lt;div&gt;<br />
            &lt;table&gt;<br />
                &lt;tr&gt;<br />
                    &lt;td class=&quot;prev&quot; title=&quot;Previous&quot;&gt;&lt;&lt;&lt;&lt;/td&gt;<br />
                    &lt;td class=&quot;next&quot; title=&quot;Next&quot;&gt;&gt;&gt;&gt;&lt;/td&gt;<br />
                &lt;/tr&gt;<br />
            &lt;/table&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Then we will apply some CSS, so that it will look nice. </p>
<p>[css]<br />
 &lt;style&gt;<br />
        #outer div {<br />
            width: 20px;<br />
            height: 20px;<br />
            border: 1px solid #ccc;<br />
            border-radius: 5px;<br />
            padding: 10px;<br />
            margin: 10px;<br />
            box-shadow: 1px 1px 1px #999;<br />
            font-style: oblique;<br />
            text-align: center;<br />
            float: left;<br />
            background: green;<br />
        }</p>
<p>        #outer .first {<br />
            background: blue;<br />
        }</p>
<p>        .prev, .next {<br />
            font-weight: bold;<br />
            font-size:30px;<br />
            padding:10px;<br />
            cursor:pointer;<br />
        }</p>
<p>        #container {<br />
            text-align: center;<br />
            width: 50%;<br />
            margin-left: 25%;<br />
        }<br />
    &lt;/style&gt;<br />
[/css]</p>
<p>Now add jQuery reference.</p>
<p>[js]<br />
&lt;script&gt;<br />
 &lt;script src=&quot;JQuery%20Versions/jquery-1.11.3.min.js&quot;&gt;&lt;/script&gt;<br />
[/js]</p>
<p>Run your page and make sure that our custom pager design is fine.</p>
<p><div id="attachment_10830" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Custom_Pager_Using_prev_and_next_In_jQuery-e1445423340334.png"><img decoding="async" aria-describedby="caption-attachment-10830" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Custom_Pager_Using_prev_and_next_In_jQuery-e1445423340334.png" alt="Custom Pager Using prev and next In jQuery" width="650" height="103" class="size-full wp-image-10830" srcset="/wp-content/uploads/2015/10/Custom_Pager_Using_prev_and_next_In_jQuery-e1445423340334.png 650w, /wp-content/uploads/2015/10/Custom_Pager_Using_prev_and_next_In_jQuery-e1445423340334-300x48.png 300w, /wp-content/uploads/2015/10/Custom_Pager_Using_prev_and_next_In_jQuery-e1445423340334-400x63.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10830" class="wp-caption-text">Custom Pager Using prev and next In jQuery</p></div></p>
<p>Now it is time to add our scripts.</p>
<p>[js]<br />
&lt;script&gt;<br />
        $(document).ready(function () {<br />
            var $first = $(&quot;.first&quot;);<br />
            var i = 0;<br />
            $(&quot;.prev&quot;).click(function () {<br />
                ++i;<br />
                if ($(&#8216;#outer div&#8217;).length / 2 &lt; i) {<br />
                    i = 0;<br />
                    $(&#8216;#outer .first&#8217;).css(&#8216;background&#8217;, &#8216;blue&#8217;);<br />
                    $first = $(&quot;.first&quot;);<br />
                } else {<br />
                    $first = $first.prev();<br />
                    $(&quot;#outer div&quot;).css(&quot;background&quot;, &quot;green&quot;);<br />
                    $first.css(&quot;background&quot;, &quot;blue&quot;);<br />
                }<br />
            });<br />
            $(&quot;.next&quot;).click(function () {<br />
                ++i;<br />
                if ($(&#8216;#outer div&#8217;).length / 2 &lt; i) {<br />
                    i = 0;<br />
                    $(&#8216;#outer .first&#8217;).css(&#8216;background&#8217;, &#8216;blue&#8217;);<br />
                    $first = $(&quot;.first&quot;);<br />
                } else {<br />
                    $first = $first.next();<br />
                    $(&quot;#outer div&quot;).css(&quot;background&quot;, &quot;green&quot;);<br />
                    $first.css(&quot;background&quot;, &quot;blue&quot;);<br />
                }<br />
            });<br />
        });<br />
    &lt;/script&gt;<br />
[/js]</p>
<p>If you notice in the code block, you can see that we are checking<em> $(&#8216;#outer div&#8217;).length / 2 < i</em> in each click. This will get true when the user clicked after the selection goes to end. We are just making the iteration to first when this occurs. </p>
<p>We are doing the above mentioned scenario both in prev click and next click. Now it is time for demo right?</p>
<p>Please see the demo here: <a href="http://sibeeshpassion.com/demo/custompager/" target="_blank">Custom Pager</a></p>
<p>That is all. We did it.</p>
<p><strong>Complete Code</strong></p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;Prev Next In jQuery &#8211; Sibeesh Passion&lt;/title&gt;<br />
    &lt;script src=&quot;http://sibeeshpassion.com/content/scripts/jquery-2.0.2.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script&gt;<br />
        $(document).ready(function () {<br />
            var $first = $(&quot;.first&quot;);<br />
            var i = 0;<br />
            $(&quot;.prev&quot;).click(function () {<br />
                ++i;<br />
                if ($(&#8216;#outer div&#8217;).length / 2 &lt; i) {<br />
                    i = 0;<br />
                    $(&#8216;#outer .first&#8217;).css(&#8216;background&#8217;, &#8216;blue&#8217;);<br />
                    $first = $(&quot;.first&quot;);<br />
                } else {<br />
                    $first = $first.prev();<br />
                    $(&quot;#outer div&quot;).css(&quot;background&quot;, &quot;green&quot;);<br />
                    $first.css(&quot;background&quot;, &quot;blue&quot;);<br />
                }<br />
            });<br />
            $(&quot;.next&quot;).click(function () {<br />
                ++i;<br />
                if ($(&#8216;#outer div&#8217;).length / 2 &lt; i) {<br />
                    i = 0;<br />
                    $(&#8216;#outer .first&#8217;).css(&#8216;background&#8217;, &#8216;blue&#8217;);<br />
                    $first = $(&quot;.first&quot;);<br />
                } else {<br />
                    $first = $first.next();<br />
                    $(&quot;#outer div&quot;).css(&quot;background&quot;, &quot;green&quot;);<br />
                    $first.css(&quot;background&quot;, &quot;blue&quot;);<br />
                }<br />
            });<br />
        });<br />
    &lt;/script&gt;<br />
    &lt;style&gt;<br />
        #outer div {<br />
            width: 20px;<br />
            height: 20px;<br />
            border: 1px solid #ccc;<br />
            border-radius: 5px;<br />
            padding: 10px;<br />
            margin: 10px;<br />
            box-shadow: 1px 1px 1px #999;<br />
            font-style: oblique;<br />
            text-align: center;<br />
            float: left;<br />
            background: green;<br />
        }</p>
<p>        #outer .first {<br />
            background: blue;<br />
        }</p>
<p>        .prev, .next {<br />
            font-weight: bold;<br />
            font-size:30px;<br />
            padding:10px;<br />
            cursor:pointer;<br />
        }</p>
<p>        #container {<br />
            text-align: center;<br />
            width: 50%;<br />
            margin-left: 25%;<br />
        }<br />
    &lt;/style&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;div id=&quot;container&quot;&gt;<br />
        &lt;div id=&quot;outer&quot;&gt;<br />
            &lt;div&gt;-6&lt;/div&gt;<br />
            &lt;div&gt;-5&lt;/div&gt;<br />
            &lt;div&gt;-4&lt;/div&gt;<br />
            &lt;div&gt;-3&lt;/div&gt;<br />
            &lt;div&gt;-2&lt;/div&gt;<br />
            &lt;div&gt;-1&lt;/div&gt;<br />
            &lt;div class=&quot;first&quot;&gt;0&lt;/div&gt;<br />
            &lt;div&gt;1&lt;/div&gt;<br />
            &lt;div&gt;2&lt;/div&gt;<br />
            &lt;div&gt;3&lt;/div&gt;<br />
            &lt;div&gt;4&lt;/div&gt;<br />
            &lt;div&gt;5&lt;/div&gt;<br />
            &lt;div&gt;6&lt;/div&gt;<br />
            &lt;div&gt;7&lt;/div&gt;<br />
        &lt;/div&gt;<br />
        &lt;div&gt;<br />
            &lt;table&gt;<br />
                &lt;tr&gt;<br />
                    &lt;td class=&quot;prev&quot; title=&quot;Previous&quot;&gt;&lt;&lt;&lt;&lt;/td&gt;<br />
                    &lt;td class=&quot;next&quot; title=&quot;Next&quot;&gt;&gt;&gt;&gt;&lt;/td&gt;<br />
                &lt;/tr&gt;<br />
            &lt;/table&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;</p>
<p>[/html]</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/custom-pager-using-prev-and-next-in-jquery/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
