Geeks With Blogs

News





The SharePoint Hillbilly Fewer Big Words... More Pretty Pictures...

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

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!

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.

Posted on Thursday, October 14, 2010 8:55 PM | Back to top


Comments on this post: jQuery in SharePoint for Hackers

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Thanks for this. I enjoy your blog.
I'd love to see your example for cloning a list item.

Couple things:

* IE and Firefox/firebug both work well for me when debugging javascript and both let you write to the console instead of using alerts (though I still use a lot of alerts).

* To create a new object, you can do:
var myObj = {};
Yup... it's exactly the same has the HashTable 'cause that's the way JavaScript works.

Keep blogging! Thanks.
Left by Kevin on Oct 15, 2010 7:45 AM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Good article, Mark!

$("#idname") works exactly the same on SharePoint pages as it does on any other Web page. This of course assumes that there is an element in the page with id="idname". I'm not sure why your experience would be any different, but revisit it!

Debugging jQuery ought to feel familiar to an old hack like you. Lots of alerts. (Used to be printf or whatever in those other languages we both used to use.) Don't try to work with jQuery without learning how to use the Developer Tools in IE8 or Firebug.

Thanks for the continued plugs of SPServices!

M.
Left by Marc D Anderson on Oct 15, 2010 5:15 PM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Wow! Nice post, but I have to ask why you stated:

$(“#ElementName”).method does not work by itself.

I use this all the time in SP without having to do what you stated so I wonder what I might be doing differently that allows it to work for me??
Left by spevilgenius on Oct 16, 2010 6:24 AM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Thanks guys.. I'm not sure why

$(“#ElementName”).method

did not work for me... I messed with it for a couple of hours and even started from scratch a few times and copy and pasted a couple of examples, so I'm not sure what I did wrong. It's good to know that it DOES work though, I will have to go back and revisit.

Great... now this is going to bug me... :)

Thanks again!
Mark
Left by Mark on Oct 16, 2010 7:01 AM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Sorry, I hope I did not sound rude! I should have asked if you were trying to reference your elements outside of an event/function such as the document ready event. I was just curious. I use SPServices a lot and several other jQuery commands but they are all inside some sort of function. Just a thought!
Left by spevilgenius on Oct 16, 2010 5:55 PM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
I didn't think you were rude at all! If there is ever something in my blog that is not 100% accurate, I WANT to know about it... this is as much about me learning too...

I am putting all my jQuery inside of a function, but did play with the document ready event in the beginning.. maybe that was my problem.

I do appreciate the insight and feedback!
Mark
Left by Mark on Oct 17, 2010 9:54 AM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
I've had the same trouble with the $(“#ElementName”).method and came to the conclusion that it is out of scope because I was using it in an Ajax processResult function call. I resorted to the getElementById method, but didn't follow that with your $(myElement).method. Thanks for that tip!
Left by DonA on Oct 23, 2010 10:07 PM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
I'd like to see a copy of the cloning code, too - could help me with what I am trying to do.
Basically I am going to be selecting a current item in a list, selecting another item in the same list, and copying most fields from one item to the next (and clearing/resetting the defaults for columns in the "source" record.)
I am thinking about using the web service to pull in each item at a time, making the copy/resets, then updating the two items.
Left by FaulstiR on Nov 15, 2010 3:42 PM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Posted a blog on the cloning code:

http://sharepointhillbilly.com/archive/2010/11/22/using-spservices-amp-jquery-to-clone-a-parent-item-and.aspx

Left by Mark on Nov 22, 2010 7:29 PM

# Hi, I love your blog
Requesting Gravatar...
Sorry for my English, so I'll be quick, do you know how i can give full privileges to my JQuery Script? Because when a User, try to create a new item in a form that use my JQuery Script, it's asks for credentials.

Please helpme.
Left by Ailema on Jan 13, 2011 9:29 AM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Mark,

Thanks for answer me, you are right, but my users have write access in the list and the SPServices works perfect, the problem is that I overwrite "_doPostBack" function, because I need execute SPService script after of submit the form, like this:

function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
TestQuery();
}
}


I mean, I need to know how I can run any script whit full privilege. I'm trying to explain me, because I don't write english well, you understand me?
Left by Ailema on Jan 13, 2011 2:43 PM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Mark:

Nice article. I have been playing around with jQuery in SP 2010 for my current project, and I discovered a "trick" using SP 2010. If you use the visual web part, you get an actual control (ASCX file), where you have total developer freedom (<SCRIPT> tags to your heart's content). No need to write it out in the render method or use the content editor web part!

I am also writing a 3-part SP and jQuery series for SharePointBriefing.com. Look for it over the next few weeks.

Thanks.
Left by Joe Mack on Feb 12, 2011 8:33 AM

# re: jQuery in SharePoint for Hackers
Requesting Gravatar...
Nice blog. We're pretty much in the same boat. Can pretty much bend sharepoint every which way using JS. I resent the fact that I HAVE to -- it makes a mockery of behaviour/presentation/business logic layer separation and usability best practices -- but at least I know I CAN.

I usually find writing and debugging JavaScript and JQuery to be very easy -- particularly in FireFox (the error console is a basic but effective tool). IE is worthless in this regard (although the IE8 debugger finally shows some promise).

However in Sharepoint this changes -- I find that parse errors are suppressed. Many runtime errors also seem to be. This obviously sucks to high heaven. I've found that (a) writing JS in a separate file which I can call from a separate, non-sharepoint page helps me to quickly discover parse errors; or (b) for code that HAS to be inline, online JSLint checkers work a charm. Runtime errors aren't so easy but judicious uses of try/catch and alerts work.

For your having to use getElementById... make sure you're wrapping your jQuery in a $(function(){}); closure, or push your function into the _spBodyOnLoad array. This way your code will only be called once the DOM is ready.

John
Left by John Wells on Mar 02, 2011 12:10 AM

Your comment:
 (will show your gravatar)


Copyright © Mark Rackley | Powered by: GeeksWithBlogs.net