5 Dec 2012

Get JSON from SQL Server


Procedure:
create procedure [dbo].[GetJSON]
(
 @table_name varchar(50),
 @registries_per_request smallint = null
)
as
begin
 if((select count(*) from information_schema.tables where table_name = @table_name) > 0)
 begin
  declare @json varchar(max),
    @line varchar(max),
    @columns varchar(max),
    @sql nvarchar(max),
    @columnNavigator varchar(50),
    @counter tinyint,
    @size varchar(10)
   
  if (@registries_per_request is null) 
  begin
   set @size = ''
  end
  else 
  begin
   set @size = 'top ' + convert(varchar, @registries_per_request)
  end
  set @columns = '{'

  declare schemaCursor cursor
  for  select column_name from information_schema.columns where table_name = @table_name
  open schemaCursor 

  fetch next from schemaCursor
  into  @columnNavigator

  select @counter = count(*) from information_schema.columns where table_name = @table_name

  while @@fetch_status = 0
  begin
   set @columns = @columns + '''''' + @columnNavigator + ''''':'''''' + convert(varchar, ' + @columnNavigator + ') + '''''''
   set @counter = @counter - 1
   if(0 != @counter) 
   begin
    set @columns = @columns + ','
   end

   fetch next from schemaCursor
   into  @columnNavigator
  end 

  set @columns =  @columns + '}'

  close  schemaCursor
  deallocate schemaCursor
  
  set @json = '['

  set @sql = 'select  ' + @size + '''' + @columns + ''' as json into tmpJsonTable from ' + @table_name
  exec sp_sqlexec @sql

  select @counter = count(*) from tmpJsonTable

  declare tmpCur cursor
  for  select * from tmpJsonTable
  open tmpCur

  fetch next from tmpCur
  into  @line

  while @@fetch_status = 0
  begin
   set @counter = @counter - 1
   set @json = @json + @line
   if ( 0 != @counter ) 
   begin
    set @json = @json + ','
   end
   
   fetch next from tmpCur
   into  @line
  end

  set @json = @json + ']'

  close  tmpCur
  deallocate tmpCur
  drop table tmpJsonTable

  select @json as json
 end
end

---------------------------------------------------------------------------------------------

When I execute it like this:
exec getJson 'announcement', 4
I'll get a single column named 'json' with *all* my data, in this case, 4 registries from a table named announcement. Something similar to this:
[{'Id':'1','Title':'<h3>1. Lorem ipsum dolor sit a','Date':'Jun 16 2008  5:44PM','Text':'<p>Lorem ipsum dolor sit amet,'},{'Id':'2','Title':'<h3>2. Quisque aliquet accumsa','Date':'Jun 16 2008  5:44PM','Text':'<p>Lorem ipsum dolor sit amet,'},{'Id':'3','Title':'<h3>3. Duis consequat laoreet<','Date':'Jun 16 2008  5:44PM','Text':'<ul><li>Duis consequat laoreet'},{'Id':'4','Title':'<h3>4. Aenean consectetuer</h3','Date':'Jun 16 2008  5:44PM','Text':'<p>Quisque aliquet accumsan le'}]
Then if you're using one JavaScript widget to slide news/announcements, it might be useful. Just pass this returning text to the eval method and you have a fresh json object, ready to use.
NOTE: it shouldn't be used with large amounts of data since you're populating a varchar sql variable, and it has a limit. If you try to pass more data than it can handle, you'll get errors.

23 Nov 2012

DELAY, SLEEP, PAUSE, WAIT ETC IN JAVASCRIPT


Today I was just looking into ways to simulate delay, sleep, pause, wait or such in JavaScript/jQuery. I’ve briefly looked into this topic before for locking a web page on timer. Here are some more thoughts on the topic. PHP has a sleep() function but JavaScript doesn’t as such. jQuery offers us both setTimeout which is similar to run a block of code after a specific time period. Well, this is because it’s useless you might say. But for simulating heavy processing and for misc performance measurements, it could be useful. So here’s how you can go about creating a sleep() in JavaScript, just a little code snippet I found somewhere.

Example of sleep function in js

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Usage

Sleep for 1 second (1000 milliseconds).
console.log(new Date());
console.log('Dude!');
sleep(1000);
console.log(new Date());

PHP to JS

Great project – essentially converting PHP function logic to JavaScript. I saw they have converted PHP’s < href="http://www.php.net/manual/en/function.time-sleep-until.php">time_sleep_until into JavaScript function below.
function time_sleep_until (timestamp) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // %          note: For study purposes. Current implementation could lock up the user's browser.
  // %          note: Expects a timestamp in seconds, so DO NOT pass in a JavaScript timestamp which are in milliseconds (e.g., new Date()) or otherwise the function will lock up the browser 1000 times longer than probably intended.
  // %          note: Consider using setTimeout() instead.
  // *     example 1: time_sleep_until(1233146501) // delays until the time indicated by the given timestamp is reached
  // *     returns 1: true
  while (new Date() < timestamp * 1000) {}
  return true;
}

//run
time_sleep_until(1233146501) // delays until the time indicated by the given timestamp is reached

Other sleepy stuff

May you could use a chained delay() function?
- trigger function after x milliseconds $("#myElement").delay(2000).trigger("click");
Or a setTimeout()…
var dotCounter = 0;
(function addDot() {
  setTimeout(function() {
    if (dotCounter++ < 10) {
      $('#dots').append('.');
      addDot();
    }
  }, 1000);
})();

JQUERY SELECTOR FIRST X ITEMS OF SPECIFIC CLASS


I’ve been playing around with this a little. Grabbing a specific number of DOM elements based on a specified class.
First, basics to get the first and last elements like so:
var firstSpan = $('span.class:first'),
    lastSpan = $('span.class:last');
To get all the elements that match a specified class like so:
var allSpans = $('span.class').get();
or the nth/xth element like so:
var firstSpan = $('span.class').get(0),
    secondSpan = $('span.class').get(1);
    //etc...
But how to get say the first 10 elements or elements 10-20?
It would be nice to go something like:
var mySpans = $('span.class').get(0,10);
Unfortunately, the .get() function doesn’t allow for a range to be passed, but just a single index. So here is an attempt to use the jQuery .get() function to include a range of elements.
(function($)
{
  //function that gets a range of dom elements against a jQuery selector
  //returns an array of dom elements
  $.fn.getRange = function(start,end)
  {
    var elems = [];
    for ( var i = start; i <= end; i++ )
    {
      elems.push(this.get(i));
    }
    return elems;
  };

  //testing
  console.log($('div').getRange(1,10));
  console.log($('div').getRange(10,20));

})(jQuery);
Does anyone know of a better way to achieve this?

22 Nov 2012

Do something after paste using jquery


Example in jsFiddle: http://jsfiddle.net/VAT83/
$(function() {
    var textValue = $('#textValue');        
    $('#textareaID')
         .bind('input propertychange', function() {
             textValue.html($(this).val());
         })
         .trigger('propertychange');
});​

Intercept paste event in Javascript


You can intercept the paste event by attaching an "onpaste" handler and get the pasted text by using "window.clipboardData.getData('Text')" in IE or "event.clipboardData.getData('text/plain')" in other browsers.
For example:
var myElement = document.getElementById('pasteElement');
myElement.onpaste = function(e) {
  var pastedText = undefined;
  if (window.clipboardData && window.clipboardData.getData) { // IE
    pastedText = window.clipboardData.getData('Text');
  } else if (e.clipboardData && e.clipboardData.getData) {
    pastedText = e.clipboardData.getData('text/plain');
  }
  alert(pastedText); // Process and handle text...
  return false; // Prevent the default handler from running.
};
you will need to use "e.originalEvent.clipboardData" if using jQuery.