5

Long time WinForm programmer here but new to the web programming scene. I have Visual Studio 2010 and I created a new WebSite project. I can't seem to get ajax to call a webmethod I created. When I click my button on the page nothing happens at all.

It looks like jquery 1.4.1 gets automatically added in a Scripts folder when I create a WebSite project.

In Default.aspx I add 2 script tags:

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript" src="Scripts/Process.js">

I put a button on the page in where the onclick function is defined in Process.js:

<input id="btnTest" type="button" value="Test" onclick="btnTest_onclick()" />

In Process.js I have the following code:

function btnTest_onclick() {

    var strData = JSON.stringify({
        userid: 5
    });

    alert(strData);

    $.ajax({
        url: 'Default.aspx/GetData',
        type: "POST",
        data: strData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: Success,
        failure: Failure,
        async: true
    });
}

function Success(data) {
    alert("success");
}

function Failure(data) {
    alert("failure");
}

In Default.aspx.cs:

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

    }

    [WebMethod()]
    public static string GetData(int id)
    {
        return "hello, my id is " + id;
    }
}
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
user441521
  • 6,942
  • 23
  • 88
  • 160
  • You know... you can always `Update-Package jquery` in console to get the latest stable version jquery (or use the UI to do the same, or even do it manually by replacing the script file) – MilkyWayJoe Nov 16 '12 at 21:33
  • 1
    also, in [$.ajax](http://api.jquery.com/jQuery.ajax/) the correct callback is `error` and not `failure`. Replace that. – MilkyWayJoe Nov 16 '12 at 21:36
  • Is 1.4.1 not stable? I guess since MS seems to automatically include it for you I assumed it must be stable. That worked in showing me that it's failing, thanks. Now I need to figure out why it's failing :) – user441521 Nov 16 '12 at 21:37
  • Does the WebMethod work if you navigate to it in your browser instead of Ajax? – Kaizen Programmer Nov 16 '12 at 21:37
  • What does the console show? F12 – Kaizen Programmer Nov 16 '12 at 21:38
  • Do you have a ScriptManager on the page with EnablePageMethods="True" – Steve Wellens Nov 16 '12 at 21:41
  • New to web dev so not sure how to nagivate to it in my browser and call it that way. Also what console? I'm doing this all from Visual Studio. I haven't published the site anywhere it's just running in VS's little self contained development server program it starts when you run (F5) from VS. – user441521 Nov 16 '12 at 21:41
  • 1.4.1 is stable, it's just very old, we're running 1.8.2 now. – MilkyWayJoe Nov 16 '12 at 21:42
  • to access the console in Visual Studio, go to Tools > Library Package Manager > Package Manager Console (but you can do the exact same thing through UI with NuGet PM) – MilkyWayJoe Nov 16 '12 at 21:43
  • hmm not seeing Library Package Manager under Tools. – user441521 Nov 16 '12 at 21:46
  • maybe you have to install [NuGet](http://nuget.org/) then – MilkyWayJoe Nov 16 '12 at 22:46

3 Answers3

5

I don't know if making Ajax request using JQuery is requirement for you, but you can more easily do ajax request to page methods using abilities of the ASP.NET ajax.

First of all I want to notice that to use PageMethods you need to add script manager control to the page and specify EnablePageMethods="True".

When you will do so, ScriptManager will render PageMethods client side definition which represent proxy of the defined page methods on the page and you can easily invoke this methods using Ajax request.

So, you can try the following code:

<asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="true" EnablePageMethods="True" />
<input id="btnTest" type="button" value="Test" onclick="btnTest_onclick()" />
<script type="text/javascript">
    function btnTest_onclick() {

        PageMethods.GetData(5, Success, Failure);
    }

    function Success(data) {
        alert("success");
        alert(data);
    }

    function Failure(data) {
        alert("failure");
    }

</script>

As you can see this code has less lines of code and it works.

Maxim Kornilov
  • 5,675
  • 1
  • 24
  • 35
  • That did work! So that shows me that my ajax call is messed up. I really would love to know what I did wrong with it though. Can you only use this for functions defined on that page? For example if I want to make a page that basically exists to store common functions to use anywhere, would this work since they exist in a page other than the one that wants to call it? The one main benefit I see is that I can specify the page a function resides on with the ajax call via 'Default.aspx/GetData'. Can I do this with the ScriptManage and PageMethods? If so I way prefer this method. – user441521 Nov 19 '12 at 21:02
  • To share some code between pages it will be better to go with Ajax enabled WCF or Web Service. The following link of Dino Esposito describes this approach: http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx. If you will review this article then you will see that working with wcf service will be same as you work with page methods. Note: you also will have access to session in wcf service methods which implemented the way it is described in article. – Maxim Kornilov Nov 19 '12 at 21:35
  • You also can review my answer to the following question: http://stackoverflow.com/questions/12886991/calling-wcf-server-from-asp-net/12992569#12992569 – Maxim Kornilov Nov 19 '12 at 21:38
  • I just started digging around with the Ajax enabled WCF and it worked also and was very easy to setup. So PageMethods work well for functionality specific to a page, Ajax enabled WCF works well with functionality for the entire website project, and Web Service would be cross website projects then I assume? Does that sound like a logical breakdown? Either way I like this way of doing it so will award you the points. Thank you! – user441521 Nov 19 '12 at 21:40
  • Yes, basically it is how things are done. Service is used for more common things, some page specific methods are placed with page definition. I am happy that this help you. – Maxim Kornilov Nov 19 '12 at 21:43
1

The data item names must match the page method arguments:

 var strData = JSON.stringify({
                id_MATCH: 5
            });

    [WebMethod()]
    public static string GetData(int id_MATCH)
    {
        return "hello, my id is " + id_MATCH;
    }
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • I named them both id and still failed. Also does anyone know how to stop IE from caching things. I made the change, reran and the alert() still said userid. I deleted temp internet files and reran and then it showed id, but it's annoying having to delete temp internet files all the time. – user441521 Nov 16 '12 at 21:58
  • 1
    Try stopping the development server between tests. Right click the notification icon in the taskbar and select stop. – Steve Wellens Nov 16 '12 at 22:01
  • That works, although is about the same number of clicks to delete temp internet files :/ – user441521 Nov 16 '12 at 22:08
0

Below is the Ajax post and the web method to process

<input id="btnTest" type="button" value="Test" onclick="btnTest_onclick()" />
<script type="text/javascript" >
function btnTest_onclick() {

var strData = JSON.stringify({
    userid: 5
});

alert(strData);

$.ajax({
    url: 'Default.aspx/GetData',
    type: "POST",
    data: strData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: Success,
    failure: Failure,
    async: true
});
}

function Success(data) {
alert("success");
}

function Failure(data) {
alert("failure");
}</script>

[System.Web.Services.WebMethod()]
    public static string GetData(int userid)
    {
        return "hello, my id is " + userid;
    } 

Could you please check the above code where the data name sent from $.ajax is same as in the webmethod.

Thanks

Sridhar Narasimhan
  • 2,643
  • 2
  • 17
  • 25