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;
    }
}
11
  • 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) Commented Nov 16, 2012 at 21:33
  • 1
    also, in $.ajax the correct callback is error and not failure. Replace that. Commented Nov 16, 2012 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 :) Commented Nov 16, 2012 at 21:37
  • Does the WebMethod work if you navigate to it in your browser instead of Ajax? Commented Nov 16, 2012 at 21:37
  • What does the console show? F12 Commented Nov 16, 2012 at 21:38

3 Answers 3

5
+50

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
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: dotnetslackers.com/articles/ajax/…. 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.
You also can review my answer to the following question: stackoverflow.com/questions/12886991/…
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!
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.
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;
    }

3 Comments

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.
Try stopping the development server between tests. Right click the notification icon in the taskbar and select stop.
That works, although is about the same number of clicks to delete temp internet files :/
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.