Refreshing a Web Part Without a Postback Using jQuery’s AJAX Function

I’ve been working on several projects with good old SharePoint 2007 (MOSS). jQuery and jQueryUI sure can spice it up nicely. Recently, I decided I wanted to refresh the contents of a Data View Web Part (DVWP) based on a user selection – a simple click on one of a big set of links – but I wanted to avoid that clunky postback.

SharePoint 2010 has the ManualRefresh capability baked right into DVWPs, but not SharePoint 2007. Besides, I wanted both the trigger for the refresh and the UX to work differently than the rather utilitarian (and never used in my experience) out of the box feel that 2010 gives you.

This is the script I came up with. In this case, I decided to show a nice message in a modal dialog using jQueryUI while I waited for the .ajax() call to complete, as I’m using an AggregateDataSource that is querying several pretty large lists. This means it takes a few seconds to come back, and the dialog saying what’s going on – not just a spinner – makes the UX more palatable.

Refreshes an element's contents on a user action, showing a modal dialog during the refresh
elementId  The id of the container element
qs         The Query String to append to the current URL
title      The title to show for the dialog
msg        The message to show in the dialog

function refreshElement(elementId, qs, title, msg) {

  var elementObj = $("#" + elementId);
  var infoDialog = $("<div><div>" + msg + "</div><div class='aaa-please-wait'></div></div>").dialog({
    open: function(event, ui) {
      $(".ui-dialog-titlebar-close").hide();  // Hide the close X
      $(this).css("overflow-y", "visible");   // Fix for the scrollbar in IE
    autoOpen: false,
    title: title,
    modal: true

  elementObj.fadeOut("slow", function() {
      async: false,
      url: window.location.pathname + qs,
      complete: function (xData) {
        newHtml = $(xData.responseText).find("#" + elementId).html();
  }).fadeIn("slow", function() {

I made the function pretty generic so that I could pass in the four arguments and use it in multiple locations if I needed to. You could really pass in the id of any element in the page. In the instance I built it for, I was passing a new value on the Query String based on what link the user clicked on, but fetching the same page with AJAX. The DVWP was set up to return different data based on the Query String parameter value.

Keep in mind that both jQuery and jQueryUI must be loaded for this to work.

The CSS for the body of the dialog is pretty simple, but here it is. The sizing worked well for me based on the image I decided to display.

.aaa-please-wait {
  background-position:center center;

What do you think? Would this make a good addition to SPServices? If so, what other options would you like me to include? If I did add it to SPServices, I’d remove the dependency on jQueryUI, as I don’t want any outside dependencies other than jQuery itself.

Enhanced by Zemanta

Updating a Lookup Column Using SharePoint’s Lists Web Service

Updating a Lookup Column Using SharePoint’s Lists Web ServiceThe SPServices discussions are a fount of interesting information. I find myself answering all sorts of questions which, while connected to SPServices, are often just as much about how SharePoint works in general. I had two questions recently about how to update Lookup columns with UpdateListItems, and I thought they would be of general interest.

Lookup column values are stored in the format “n;#Text Value”, where n is the ID of the value in the reference list and “Text Value” is, well, the text value of the Lookup column. There are probably some good historical reasons for this having to do with Office compatibility, if you think about it. Just storing the text value means that you lose the connection to the original item in the reference list, and just storing the ID for the item would mean that you’d need expensive calls to the database every time you wanted to display the value. As for the ‘;#’ delimiter, you see that sprinkled throughout how SharePoint stores data values. It’s probably related to some very old standard of some sort, but in any case it’s highly likely to be a unique string which no one will use in their text values, so it’s a reasonable delimiter.

Update a Lookup Column Value

The first question was how to update a Lookup column value. The code for this in SPServices is pretty straightforward; the tricky bit is knowing how to structure your value.

In this example, the State column in Sales Opportunities is a Lookup column to the Title column in a list called States.

    operation: "UpdateListItems",
    async: false,
    listName: "Sales Opportunities",
    ID: 5,
    valuepairs: [["State", "2;#Rhode Island"]],
    completefunc: function (xData, Status) {

It also works fine to just specify the index:

    valuepairs: [["State", "2"]],

The trick is knowing what the right index is. You’ll need to figure that out by calling GetListItems on the reference list or by using some other method.

“Emptying” a Lookup Column Value

The second question was how to “empty”, or remove, a previously set value in a Lookup column.

    operation: "UpdateListItems",
    async: false,
    listName: "Sales Opportunities",
    ID: 5,
    valuepairs: [["State", ""]],
    completefunc: function (xData, Status) {

It’s important to keep in mind that when you are interacting with SharePoint’s XML (SOAP) Web Services, *all* of the traffic back and forth is text. There’s no such thing as a null or some of the other datatypes you might be used to in other ways of interating with the API. An empty string [“”] in text essentially *is* a null; it represents “no value”.

I wish that I could say that this little tip was foolproof in interacting with all of SharePoint’s Web Services, but I can’t. There is a *lot* of internal inconsistency across the Web Services, and in some cases, even among operations in the same Web Service. If you want to set other values to “empty” or “null”, you may need to experiment to see what works. I didn’t write ’em; I just wrapped ’em! Note that the line:


can be an absolute lifesaver. It will alert what has come back from the server as a response to the Web Service call. Even if the AJAX request is successful (Status=”success”), there may be useful (or totally indecipherable) error information in the response.

How to Fix "Sys.ArgumentTypeException: Object of type ‘Sys._Application’ cannot be converted to type ‘Sys._Application’." Error

Image representing NewsGator as depicted in Cr...

Image via CrunchBase

In one of my client projects, we kept seeing this error, and basically ignored it for a long time. In our case, we saw the errors specifically on pages that included NewsGator Web Parts and we thought they might be the problem, but it was actually a problem with the SharePoint AJAX settings which NewsGator would have initially installed, but which had been changed many times by other installs and/or people.

A typical full error looked like this:
Sys.ArgumentTypeException: Object of type 'Sys._Application' cannot be converted to type 'Sys._Application'.
Parameter name: instance  ScriptResource.axd?d=3OFwNP2OqissPVnq69wL3hN2bp71o6_alyDiAQ4AtZb7FI9MYnlhIQdNZXDeHZVNPXrWlmYq-0mnuHvEHRe7gW131sU6muSFCaVlWX7ED1k1&t=45c7299c, line 1559 character 43

I did a lot of searching on the Web, of course. Everything I found seemed to be from 2007 or earlier and have to do with asp:ScriptManager. Most of the suggestions said to set the ScriptMode attribute of ScriptManager to Release, so from this:

<%--<asp:ScriptManager ID="ScriptManager1" runat="server" />—%>

to this:

<%--<asp:ScriptManager ID="ScriptManager1" ScriptMode="Release" runat="server" />—%>

This didn’t have any effect for us, unfortunately. FYI – the ScriptManager will be in your master page if you have SharePoint AJAX enabled.

After a *lot* more fishing around (I get tenacious with this stuff once I start – I don’t like to see *any* error messages, because they tend to “cascade” on you.) I found the problem.

In this case, the web.config file had been built up over time with little documentation of the steps involved, who did what, etc.  In other words, pretty much the usual state.  SharePoint had been put out there, its use expanded virally, they tried a lot of different third party things, some of which stayed and others were removed, etc.

Somehow in all of that back and forth, in the line highlighted below, debug had been set to “true”. Setting it to “false” fixed the problem.

<globalization fileEncoding="utf-8" />
    <compilation batch="false" debug="false">
        <add assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <remove expressionPrefix="Resources" />
        <add expressionPrefix="Resources" type="Microsoft.SharePoint.SPResourceExpressionBuilder, Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <add expressionPrefix="SPHtmlEncodedResources" type="Microsoft.SharePoint.SPHtmlEncodedResourceExpressionBuilder, Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <add expressionPrefix="SPSimpleFormattingEncodedResources" type="Microsoft.SharePoint.SPSimpleFormattingEncodedResourceExpressionBuilder, Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <add expressionPrefix="SPUrl" type="Microsoft.SharePoint.Publishing.WebControls.SPUrlExpressionBuilder, Microsoft.SharePoint.Publishing, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

Demo Page: Using jQuery to Update an Item Without A Form

Last week, I spotted a really nice blog post from Mike Oryszak which showed how to update an item without a form by using jQuery to post changes using the SharePoint Lists Web Service. It got me thinking about a lot of things that you might do to make SharePoint feel more “Web 2.0”.  By using jQuery, you can quickly add functionality to your pages, and in this case, even use its AJAX capabilities to talk to Web Services.

I’ve created a new demo page on the Sympraxis Consulting demo site which ought to give you an idea of some of the possibilities.  The page shows how you can use SharePoint’s Lists Web Service and jQuery to update items in real time, without a roundtrip to the server.

imageEach row in the Data View Web part has buttons which allow you to increase/decrease the Potential Value column by either $1 or $10.  On each button click, there is a SOAP call to the Lists Web Service (_vti_bin/Lists.asmx, UpdateListItems operation) which updates the item.  The jQuery code then updates the value on the page and changes the fontStyle to italic.

After some DMs back and forth with Mike, at his suggestion (and for extra fun), we used the Tablesorter 2.0 jQuery library so that the table re-sorts after each Potential Value change. A bonus effect of this is that the column headers are sortable as well.  The CSS styling on the headers shows this.

A known issue (which we chose not to deal with here) is that concurrent changes will write over each other.  There is no checking for these conditions, though they could be managed fairly easily.

Take a look and let me know what you think!