jQuery in SharePoint for Hackers

Originally posted on: http://geekswithblogs.net/SoYouKnow/archive/2010/10/14/jquery-in-sharepoint-for-hackers.aspx

jQU3|2y |N Sh/-\|23PO|/\/7 4 HA(kERS

 

Remember when Angelina Jolie was less of a freak? When cell phones were still relatively new and there existed things called “Pay Phones”? Well.. that has absolutely nothing to do with this blog post. Sorry…

 

Not THAT kind of Hacker

So… when it comes to writing code I can admit that I’m not a classically trained developer. My first computer was a Commodore SX-64 when I was about 11. Wow, I’m a geek. I would enter programs from the Code magazines and then change them around to see how they worked.  I would pull out the graph paper to map out coordinates for those awesome graphics. In college I took Fortan, C, and this new thing called Visual Basic. I learned how to create linked lists, use inline assembly to write directly to the video card, the basics of OO, and myriad of other concepts… then I entered the real world. My first job was for a start-up company that had built an application in Visual Basic that they wanted me to re-write using Delphi (Think OO VB in Pascal). My next job entailed writing Windows Device drivers, BIOS code, and applications for trade shows in something called C++ Builder. Then I entered the world of consulting during the tech boom years working with Tcl/Tk, embedded C, Java, and the first version of C#. After the tech bust came the dark years where I was stuck writing ASP (not ASP.NET) until I landed with another start-up firm writing commercial software in Java. Then, finally, in 2007 SharePoint was thrown into my lap. Add in some BA, PM, and Architecture work and you should be getting the picture? I’m a Jack-of-all-Trades / Master-of-None developer… a hack..  a mantle I wear proudly.

I might not be able to eloquently detail the nuances of some obscure .NET class, but I’m able to look at problems from a technology agnostic perspective and find solutions that would elude other developers. How many C# developers have ever written a HTTP response handler for a web service?   Maybe that’s why I’ve gravitated to SharePoint and decided to devote so much time to this technology. It’s literally not possible to just be hack and figure all this stuff out. Don’t get me wrong, you can hack your way into some cool sh… stuff (like hopefully stuff in this blog which I will get to I promise), but in SharePoint more so than in any technology I’ve faced before you need to understand the why’s and the how’s more deeply.  Let’s face it, there are a LOT of how’s in SharePoint and even more why’s (and why not’s).  Sorry for the rambling.. I do that sometimes… must be too much coffee… mmmmmm….. coffee….

Are you EVER going to get to the point?

Oh yes.. the point of this blog… jQuery and SharePoint from a hackers perspective. For better or for worse my career has led me down the path of “You have a project due using technology ‘x’, and it’s already two weeks late.” as opposed to “hey, take a couple of weeks and learn how to do ‘x’” or “We’re sending you to be trained in ‘y’.”  Secretly, I like the challenge although it would be nice to get more formal training sometimes as well (in case anyone is reading this who as the authority to approve the budget 🙂 )

Wow.. I started rambling again, didn’t I? Well.. that’s one of the reasons you like my blog? right? I could be dry and boring like some of those articles you’ll find on some web site that I won’t mention.. but why should you be bored to death?

Where was I? oh yeah… jQuery. I’ve seen jQuery used and copy and pasted some examples before, but I’ve never jumped in and tried to use it until about 3 weeks ago… and let me tell you it’s really cool… and it’s really a pain. If I would have had time and been smart I probably would have spent some time learning the in’s and out’s of jQuery first by doing something like wathing these videos:   jQuery for Absolute Beginners Video Series

However, that would have made way too much sense and I am a hacker.. remember? Plus there appear to be a few nuances that make working with jQuery just a little more difficult when you throw SharePoint into the mix.  So, rather than give you a tutorial on jQuery, I’m going to give you some tips and tricks to get started immediately writing jQuery for SharePoint, you can always go back and really learn it later… right???

Beating the Dead Horse – Performance with jQuery

I have said this before, and I’ll say it again.  Please be wary of performance issues when using jQuery. If performance is a key requirement for your application, I’m not sure I can endorse jQuery. It can be slow, and on older computers it will be even slower. Remember, it’s executed on the client, not the server. Sometimes you have limitations on writing managed code and that is when jQuery is a life saver, don’t dismiss managed code though. Managed code is faster, more ‘private’ (in jQuery you are exposing your business logic), easier to debug, and more powerful (try using SPServices for writing data as an anonymous user or elevating privileges).

So.. what can I do with SharePoint and jQuery

The question should be, what can you NOT do with jQuery? In my previous blog post I get by with a little help from jQuery and SPServices… I introduce you to an awesome jQuery library called SPServices and walk you through setting it up.  SPServices allows you to call SharePoint Web Services using jQuery.  That’s awesome. You now can do custom reads and writes and rollup reporting that before you could not do without managed code.  Throw in all of the awesome jQuery packages out there and do you even NEED to write managed code? (yes you DO by the way).  In the past three weeks I’ve been able to:

  • Create various interactive pie and bar charts
  • “Clone” a parent list entry and all its children –> Blogged about it here: Using SPServices & jQuery to Clone a Parent Item and All its Children
  • Create vertical and horizontal accordions for displaying data
  • Create stylized tables joining data from several lists that filter and sort in memory

Historically all of those items have not been possible without deploying something to your farm or writing web services of some kind.

Blah.. blah.. blah.. I get it.. jQuery is cool… how about those tips and tricks you were talking about?

Okay… so, like me, you want to just dive in and start DOING jQuery.  I do highly recommend you read through some tutorials and get a solid foundation for any technology you learn, but if you really just want to get started here are some basics.  Like everything else, I try to keep things as simple as possible, so you won’t typically see me use lots of acronyms or even refer to them if they are not relevant to the basics here… I mean, do you really care what the DOM is if you just want to get your pie chart to work? 

The Very Basics

Again, referring to my earlier post I get by with a little help from jQuery and SPServices…, you will need:

  1. The main jQuery library stored on your file system or document library
  2. Any other libraries you wish to work with (like SPServices) also on file system or document library
  3. A Content Editor Web Part for your JavaScript (I DON’T recommend putting it straight in your Master Page in SPD ESPECIALLY if you don’t package and deploy your Master Pages)

Working with Elements

One of the little nuances I have encountered when working with jQuery in SharePoint is that many of the jQuery libraries reference elements using

$(“#ElementName”).method

I quickly discovered that this would not work in SharePoint because, well… because it never worked and “$(“#ElementName”)” always returned “undefined”. This is mostly likely because of the scope of the elements and “#ElementName” not searching the entire DOM… oh crap.. I swore I wouldn’t use that acronym…

What I had to do was get the element by it’s ID before using it by doing (and it works EVERY time):

var myElement = document.getElementById(“idOfElement”);
$(myElement).method

<UPDATE>

A couple of helpful people have indicated that you SHOULD be able to get the element using ‘$(“#ElementName”)’ without issue in SharePoint. I will have to investigate why this was not working for me. (I love SharePoint).  However, if you do ever have a problem getting your element, you might try getElementById and see if that helps.  Thanks again for taking the time to let me know when I’m smoking crack!

</UPDATE>

Once you have your element, you can easily read and write the contents of it whether it is a div, table, a table row, or whatever:

//Getting element
var myElement = document.getElementById(“idOfElement”);
$(myElement).method

//Reading contents of an element
// div / table / etc...
var contents = $(myElement).html();

//inputs
var contents = $(myElement).value;

//writing content to an element
//div / table /etc...
$(myElement).html("content goes here");

//inputs
$(myElement).value = "hello world";

I know it sounds simplistic, but that little knowledge right there is the key to working with many jQuery libraries you will encounter. jQuery packages generally stylize a certain div or table or some other element, and because you will many times be building these elements on the fly it is important to be able to get and set these elements.

Working with variables and objects

So, since you will be using a cool tool like SPServices to retrieve and roll up your SharePoint data it is important that you know how to store this data in such a way that allows you to retrieve it as necessary.  Here are some ways of storing data (if you know of better ones, that comment section is there for a reason).

HashTables

Okay.. so there really aren’t “real” HashTables in Javascript, but you can get the same functionality quite easily as follows:

//initialize variable
var hashTable = {};

//add key value pair
hashTable[key] = value;

//iterate through HashTable
for (key in hashTable)
{
    alert("This is my key: " + key " and this is my value:" + hashTable[key]);
}
Objects

Objects are easy to use as well, don’t over complicate them in your mind… remember.. KISS

//create object
myObject = new Object;

//properties are created by setting them
// "thisValue" will be undefined below
var thisValue = myObject.propertyName;

//now "thisValue" will be "Hello World"
myObject.propertyName = "Hello World";
var thisValue = myObject.propertyName;

//and just like a HashTable you are used to, you can store this object the same way
var hashTable = {};

hashTable[key] = myObject;

Helpful at all? Again, a lot of this is just stuff I figured out from hacking and reading the interwebs, if you know of better methods, PLEASE enlighten all of us?

Other minutia helpful with SharePoint

Many of the fields returned from SharePoint Web Services have a value of some number, a semicolon, a hash, and the value like “12;#Hello World”.  Generally, this is the ID field followd by the value.  So, “split” becomes your friend here:

//get field from web service call
var fieldValue = $(this).attr("ows_FieldName")

//strip off ID
var thisID = (fieldValue.split(";"))[0];

//string off Value
var thisValue = (fieldValue.split("#"))[1];

Another headache you will find is doing simple math. Using “thisID” from the example above:

//let's add 1 to thisID (assuming this ID == 1)

var value = thisID + 1;
//value == "11" because thisID is treated as a string 

var value = (thisID*1) + 1;
//value == 2, multiplying the string by 1 converts it to a number

So, there you go.  There’s some basics for manipulating the data in returned from SPServices. Nothing earth shattering, but hopefully it will lighten your load.

Debugging

All I can say is that debugging your jQuery/JavaScript sucks… it’s horrible.. it’s horrendous… I hate it with the fire of several suns…   Sometimes you will get an erroneous error with a line number that is completely inaccurate, other times you will get NO error at all.  Your code just won’t work!  I don’t know of any intuitive free IDE that will check your JavaScript for errors.. do you?  I find that NotePad++ does the best job coloring the syntax and helping you match your braces though.  Here are a few tips to make debugging not quite as painful, but you still want to pull your hair out:

Develop in small chunks and backup often

Don’t EVER sit down and write 100 lines of JavaScript without testing. Write small chunks at a time and as soon as you have SOMETHING working, save it so you can easily roll back to it WHEN you break your code.

Alerts are your friend

Use alerts with debug information often. It will help you determine where your code is failing or if your code is even getting executed.

Check for the usual suspects

So, I find that I do a lot of the same mistakes over and over which has also helped me find problems.  Before shooting yourself because you can’t find the problem, check for these “oh crap.. I can’t believe I did that” mistakes:

  • Missing braces
  • Not ending a line with a semi-colon or accidentally putting a colon
  • Not initializing or setting a variable before using it
  • Missing quotation mark
  • Incorrect path to JavaScript library
  • Incorrect element id
  • Wrong case on methods.. it’s NOT  “GetElementByID” it’s “getElementById”

Like I said, debugging in this environment sucks and definitely takes getting used to, but with some time, patience, and frequent backups you’ll be okay. If not, give me a call, I have reasonable rates. 🙂

That’s all for now folks

So, yeah, there you go. Enough information to make you dangerous and help you get over some common hurdles. Have fun and use it wisely, there’s some eye popping stuff at your fingertips.  Lastly, please don’t be afraid to get in there and break stuff and play. Let’s face it, a lot of us do this type of work because we enjoy it. So have don’t be afraid to get your hands dirty, you’ll be amazed at what you can pull off with a little patience.

Have any suggestions to add? any insights? I’m still learning, so any help is greatly appreciated!  Thanks again for stopping by.

Families in Germany who are facing divers soundness problem, such persons can buy drugs from the Web without prescription. With the market flooded with divers web-sites selling sundry medicaments, purchasing medicines from th WEB is no longer a trouble for common man. Certain medications are used to treat infections caused by dental abscesses. Of course it isn’t all. If you’re concerned about erectile soundness problem, you probably know about Xenical and Hoodia. Probably each adult knows about Garcinia. (Read more PhentermineXenical). The symptoms of sexual health problems in men include impossibility to have an erection sufficient for sexual functioning. Certain medications may add to sex drive difficulties, so its substantial to cooperate with your soundness care professional so that the prescription can be tailored to your needs. Preparatory to grab Levitra or other medicament, speak to your druggist if you have any allergies. Talk to your health care provider for more details. Preparatory to ordering this remedy, tell your physician if you are allergic to anything.