Supporters of End User
Web

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

Item is currently unrated. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.
Categories:MOSS; WSS; 2007; 2010; Content Editor Web Part; SharePoint Designer; Data View Web Part; Javascript and jQuery; Solutions with Tools; Scripted Solution; Site Manager/Power User

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: mrackley@gmail.com
Twitter: http://www.twitter.com/mrackley

[tweet]

Comments

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: