1,804 articles and 14,751 comments as of Friday, April 1st, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Tuesday, October 26, 2010

I get by with a little help from jQuery and SPServices…

Mark RackleyGuest Author: Mark Rackley
The SharePoint Hillbilly

So.. unless you’ve been living under a rock (or in Arkansas) you have no doubt read a billion blogs (well, maybe not a billion) about using jQuery in SharePoint.  You’ve also probably read several more on the great tool at CodePlex called SPServices created by Mr. Marc Anderson. Maybe you’ve played with both? Maybe you’ve grappled with trying to find a real world scenario for when you would use them?

Well.. I’ve been doing a lot lately with SPServices in SharePoint because I’m starting to deal with clients that do not allow any managed code on their servers or we have to go through an arduous process to get managed code approved.  I’ve got a couple of pretty interesting SPServices and jQuery blogs up my sleeve, but I wanted to write a more simple easy to follow blog first so that you can get an introduction to SPServices if you are new to it.

So? What are we going to do?

Think back to one of my earlier blog posts on creating a Parent/Child list relationship:

Creating a SharePoint List Parent/Child Relationship – VIDEO REMIX

In this blog I created a DataViewWebPart to display time entries associated with an issue:


How about we add some functionality so that a user can delete one of the time entries from this page without having to go to the EditForm for the Time entry or use the drop down menu? How about we add a “delete” button to each row that a user can click to delete that row? Yes.. I know… not a great reason to do this in this scenario. I don’t want to see your whiny comments saying I should have done it another the way.  The point of this blog is to introduce you to SPServices.. got it? If you don’t like it, let me show you a really funny kitten video by clicking HERE

Are they gone yet? good… okay… so… let’s get started.

A few comments about SPServices and jQuery

So… first thing you need to do is download the jQuery library and the SPServices library.

  • SPServices – Click the download link
  • jQuery 1.4.1 – The current release is 1.4.2, but I’m using 1.4.1 in all my examples.

Next you will need to put these javascript files some place that you can access them in SharePoint. DO NOT reference them from some 3rd party web site. It will affect your performance and if their site goes down for any reason then your functionality is broken. You have two options for putting these on your SharePoint farm, each come with a positive and a negative:

Place files in a document library

You can put your files in a document library that all your users will have access too.  This has the benefit of easily being able to upload new version of a javascript file or quickly tweak existing one.  The downside is that you will take a slight performance hit from storing them in the content database.

Deploy files to the file system

Yes.. I said DEPLOY (don’t manually copy).  By storing your javascript files on the file system you get the benefit of improved performance, but you lose the flexibility of being able to upgrade and modify the files as easily as if they were in a document library.

Don’t know how to deploy? Well, now you can take advantage of one of my other blog posts:

Creating SharePoint Solution Packages! So easy an Admin can do it!

Typically, especially for development I just place my javascript files in a document library.  So, for the sake of this demo, I’ll upload them to a document library called scripts:


A quick caveat about jQuery

Yes… jQuery is awesome, and yes it will help you do some really cool stuff that you wouldn’t be able to do without managed code,but please keep in mind that jQuery and all javascript is executed on the CLIENT’s computer, not the server. This means you cannot guarantee the performance of your javascript on someone else’s crappy old computer. If you abuse javascript, your users’s perforamnce and experience will suffer. Use it wisely, use minimized files whenever possible, and just be aware of this please.

Okay… what’s next?

Okay… next thing we need to do is drop a Content Edit Web Part AT THE BOTTOM of our page. Please note, that I have more than once failed to place the CEWP at the bottom of the page which will prevent you from being able to call your javascript functions. That’s a fun one to debug the first time you run into it.


Now let’s write our jQuery that will delete a time entry. We will need to know the ID of the time entry in order to delete it.  Let’s not worry about how we’re going to get that right now. Let’s just hard code something for testing.  So, using SPServices our jQuery will look like the following:

//load our scripts
<SCRIPT type=text/javascript src="../../scripts/jquery-1.4.1.min.js"></SCRIPT>
<SCRIPT type=text/javascript src="../../scripts/jquery.SPServices-0.5.6.js"></SCRIPT>
<SCRIPT type=text/javascript>

function DeleteTimeEntry(timeEntryID)
{

//Set cursor to hourglass
document.body.style.cursor = "wait";

//we will be executing the SharePoint WebService "UpdateListItems" with the Command "Delete" to delete
//a list entry from the list “Time”  

     $().SPServices({
      operation: "UpdateListItems",
      async: false,
      listName: "Time",
      updates: "<Batch OnError='Continue' PreCalc='TRUE'>" +
                "<Method ID='1' Cmd='Delete'>" +
                    "<Field Name='ID'>" + timeEntryID +  "</Field>" +
                "</Method>" +
            "</Batch>",
        completefunc: function (xData, Status) {
                                                //check for errors here
                        //reload the page after the deletion has occurred
            window.location = window.location;
        }
     });

 //Turn hourglass off
  document.body.style.cursor = "default";
 }

 </SCRIPT>

Pretty simple? It’s basically just one call.  We pass in the ID for the Time entry (timeEntryID) we want to delete, and SPServices executes the UpdateListItems Web Service method to delete that entry from the list called “Time”, and then we reload the page. So, place the above script in your CEWP by either Clicking on the “Source Editor” button from the CEWP’s property pane or upload this script to your scripts document library and reference it in the “Content Link” of your CEWP.  Again, for development purposes I usually just copy and paste it into the CEWP:


You can actually test this code by creating an HTML button at the bottom of your script and passing in a hard coded Time Entry ID that you know exists. For instance, I know that for my screen shot up there “Title 3” has an ID of 6.  So my test button would look like:

<input type=button value="Delete a Time Entry" onclick="javascript:DeleteTimeEntry('6')">

Before button click:


After button click:


By the way, if you get the error “Object Expected” it generally means that the path to your javascript files is not correct and they did not get loaded.

Okay.. that’s all fine and dandy, but what we really want is to put a delete button on each row of the Time list that will automatically pass in the correct Time entry ID.  To accomplish this we are going to tweak our DVWP is SharePoint Designer. So, go ahead and open up the site in SPD.

Modify DVWP

Okay.. let’s add a column for our button to the Time list DVWP. If you haven’t done so already, make your DVWP show sample data so that it’s easier to work with:


Now click on the word “Title” in the DVWP, then Right click on “Title” and select “Insert->Column to the Left”


This will create an empty column for us to put our delete button in:


Next click on one of the empty cells in your new column and SPD should bring you to the corresponding location in your code for that cell. I wish SharePoint was always consistent, but it’s not.  In my DVWP the code looked like:

 <td class="ms-vb">
                <xsl:text xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" ddwrt:nbsp-preserve="yes" disable-output-escaping="yes">&amp;nbsp;</xsl:text>
            </td>

Go ahead and delete that whole line between the <td> and </td> we don’t want that.  We want to put a button there that calls our javascript.  It will look something like:

           <td class="ms-vb">
                <input type="button" value="Delete" onclick="javascript:DeleteTimeEntry('6');" />
            </td>

However we need to pass in the ID of Time entry and not the hard coded “6” from our test button.  This turns out to be super easy to do, because we are in our DVWP we can specify the ID for the row we are on by using “{@ID}”.  this is very similar to what we did in the Parent/Child post referenced above in case you need step by step instructions on how to do this.  Anyway, the resulting cell looks like:

 <td class="ms-vb">
                <input type="button" value="Delete" onclick="javascript:DeleteTimeEntry('{@ID}');" />
            </td>


And that’s it! We’re done! Simply load your page in SharePoint and click one of the delete buttons. The page should reload fairly quickly with the corresponding Time entry deleted”:


By the way, don’t forget to remove your test button at the bottom of the page.

So there you go! Not exactly rocket science, but hopefully a fairly non-threatening introduction to SPServices and jQuery in SharePoint.

Please stay tuned for more, I cannot and will not promise that it will not get much more hairy from here.

As always, let me know if I need to elaborate on anything. If you find yourself completely lost, go back and view: Creating a SharePoint List Parent/Child Relationship – VIDEO REMIX then come back here and everything should make much more sense.

Cheers!

Mark RackleyGuest Author: Mark Rackley
The SharePoint Hillbilly

Mark has been developing software applications for over 15 years filling the roles of Project Manager, Business Analyst, Lead Developer, and Software Architect. He has been involved in projects for such companies as Dell, Motorola, Intel and Agilent Technologies. He has worked in large corporate environments, small software start-ups, and as a consultant. Mark currently works for Juniper Strategy, LLC as a Solutions Architect making key SharePoint architecture and development decisions as well as bringing the appropriate SharePoint Best Practices to his clients and customers.

Mark’s goal as a speaker, blogger, and author is to help every new architect and developer avoid the frustrations and brick walls he ran into while learning SharePoint.

Blog:  http://www.sharepointhillbilly.com
Email: [email protected]
Twitter: http://www.twitter.com/mrackley

 

Please Join the Discussion

10 Responses to “I get by with a little help from jQuery and SPServices…”
  1. tyler says:

    is their another alternative to add the column to the DVWP rather than using SharePoint Designer or Visual Studio? There are soo many great examples I’d love to use but our company naively blocks SPD.

    • Matt Bramer says:

      You *can* build a DVWP by hand if you would ever have the desire to. Christophe has a CrossList creator on his SPToolKit that could get you started. You *could* do this, but it’s a lot of work. Actually, I think this is how Marc became so proficient at XSL. Digging into the guts of XSL is a bit of a head-basher at times, but I’ve found it to be worth it’s weight in gold.

  2. Kerri says:

    Mark, I’ve been spending a lot of time lurking around The Sharepoint Hillbilly lately, and I always leave with a smile! Thanks for this article, it is just what I needed. Like Tyler, my company has blocked SPD to anyone outside IT. They have only recently caved under my constant badgering and granted me access. Which means I have a boat load of catch-up to accomplish! This is going to be the winter of mastering SPD, and your example here fits perfectly into my immediate need, this is a great jumping off point for me. Thanks for the push!

  3. Greg says:

    Mark,
    It is always with great pleasure that I read and re-read your articles and watch your videos.
    They are always both entertaining (I couldn’t see the kitten video, snif…) and of great use.
    Coupling that with the awesomeness of the SPServices library and you get articles that are
    true gems.
    Thanks for sharing them!

    Greg

    PS: Going to go back at your whole series and will post back if anything is unclear.

  4. Mark Rackley says:

    Thanks for the kind words guys! Always nice to know that I’m adding some value however limited. :)

    Tyler, you don’t have to use a DVWP, you can create your own table view using jQuery and some sort of jQuery data table library, then you have complete control over it without needing SPD or managed code.. I’ve used the one from http://www.datatables.net/ and it has a lot of nice sorting and filter features.

    • tyler says:

      Hi Mark –
      Thanks for the datatables link, I have yet to hear of it! I’ll check it out..

      Do you have any SharePoint and datatables working examples?

  5. Trudy Hutzler says:

    How does this work with SharePoint Foundation?

  6. Mike says:

    So if I want to say copy the entire list contents to another list instead of doing a delete how do I pass all of the fields to the new list? I have it updating the new list, only it only sends the ID and nothing else.

  7. Sajimon says:

    Hi Mark,

    I have a question on using Flash files on Sharepoint 2007.

    Can I add flash files to run in a site without adding any code (OOB feature)?

    Thanks,
    Saji


Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!