Jquery – Sharepoint 2010 JQuery Ajax not working

jquerysharepointsharepoint-2010

I have a custom webpart within Sharepoint and am trying to apply some ajax to the webpart.

The same code works within a .net web application but not within a sharepoint web part.

The code from the .net web application is shown below (the aspx page and the code behind) which works fine.:

ASPX File

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  // Add the page method call as an onclick handler for the div.
    $("#Result").click(function () {
        var loc = window.location.href;
    $.ajax({
      type: "POST",
      url: loc + "/GetMessage",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        // Replace the div's content with the page method's return.
        $("#Result").text(msg.d);
      }
    });
  });
});

   </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div id="Result">Click here for the time.</div>
    <asp:Button ID="btnClick" runat="server" Text="Button" />
</asp:Content>

.CS File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace WebApplication3
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static string GetMessage()
        {
            return "Codebehind method call...";
        }
        [WebMethod]
        public static string GetDate()
        {
            return DateTime.Now.ToString();
        }
    }
}

The text "Click here for the time" changes to "Code behind method call" when I click on it without doing a postback. I can step into the code and this calls the method GetMessage() in the code behind within a .net web application.

However this does not work on a webpart within sharepoint 2010. Does anyone have any ideas?

Best Answer

Another option is to create a SharePoint Application Page. Here is your code slightly modified to work as an Application Page (uses SharePoint Master Page content sections, and the AJAX points to the application page:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ApplicationPageWS.aspx.cs" Inherits="WebMethod.Layouts.WebMethod.ApplicationPageWS" DynamicMasterPageFile="~masterurl/default.master" %>


<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Localizable="false" Name="js/jquery-1.8.2.js"></SharePoint:ScriptLink>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<script type="text/javascript">
    $(document).ready(function () {
        // Add the page method call as an onclick handler for the div.
        $("#Result").click(function () {

            $.ajax({
                type: "POST",
                url: "**/_layouts/WebMethod/ApplicationPageWS.aspx/GetMessage**",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#Result").text(msg.d);
                },
                error: function (msg) {
                    alert(msg.responseText);
                }
            });
        });
    });
</script>

<div id="Result">Click here for the time.</div>
<asp:Button ID="btnClick" runat="server" Text="Button" />

</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
     Application Page
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
    My Application Page
 </asp:Content>

Next change your service-side to inherit from LayoutsPageBase instead of WebPart:

using System;
using System.Web.UI;
using System.Web.Services;
using Microsoft.SharePoint.WebControls;

namespace WebMethod.Layouts.WebMethod
{
    public partial class ApplicationPageWS : LayoutsPageBase
    {
        protected override void OnInit(EventArgs e)
        {
             base.OnInit(e);
             //InitializeControl();
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string GetMessage()
    {
        return "Codebehind method call...";
    }

    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }
}

}

Hope this solution work in your situation, if not, and you need to call a web service from a web part, you will need to create the web service outside of your Web Part. This is nicely explained at http://dbremes.wordpress.com/2011/01/03/ajax-style-web-parts-in-sharepoint-the-easy-way/

Steve