Solved

Jquery AJAX and ASP.NET WebMethod

Posted on 2014-02-26
10
1,550 Views
Last Modified: 2014-03-05
Hi All,

I'm trying to use AJAX to check whether usernames are available on a web form in our asp.ner site.

Iwant to use AJAX with Jquery to query the db but the code I have isnt working and is giving no clear indication as to why its not working?

on my default.aspx page i have the following;

<asp:TextBox ID="UsernameTextbox" runat="server"></asp:TextBox>

    <script type="text/javascript">
        $('#<%=UsernameTextbox.ClientID%>').watermark('Username');

        $('#<%=UsernameTextbox.ClientID%>').blur(function () {
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "default.aspx.cs/CheckUsername",
                    data: JSON.stringify({ username: $('#<%=UsernameTextbox.ClientID%>').val() }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data) {
                            alert('username available');
                        }
                        else {
                            alert('Username already exist');
                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                });
            });
        });
    </script>

Open in new window


and my webmethod is currently as follows in the default.aspx.cs;

    [WebMethod]
    protected bool CheckUsername(string username)
    {
        detailsTableAdapter detailsAdapter = new detailsTableAdapter();
        detailsAdapter.UsernameExists(username);
        detailsAdapter.Dispose();
        return true;
    }

Open in new window


Ive added a breakpoint to see if the webmethod is being called on the detailsAdapter.UsernameExists(username); line, but its doesnt break here.

In the error print out I get 403 and Forbidden as msgs. Coud anyone direct as to whats going wrong please?

I would like to add that this is only accessing the local site on my machine and is not referencing any external URLs?
0
Comment
Question by:flynny
  • 6
  • 4
10 Comments
 
LVL 19

Expert Comment

by:Melih SARICA
ID: 39888521
try changing
[WebMethod]
    protected bool CheckUsername(string username)
    {


to
[WebMethod]
    public bool CheckUsername(string username)
    {

protected to public
0
 

Author Comment

by:flynny
ID: 39888543
changed it but still getting the fordbidden error?
0
 
LVL 19

Expert Comment

by:Melih SARICA
ID: 39888573
try default.aspx/CheckUsername
0
 

Author Comment

by:flynny
ID: 39888701
great that has changed things.

I now get a 200 error? SyntaxError: JSON.parse: unexpected character?

any ideas what this means?

Its still not running the webmethod as I added a line to change the text in one of the text boxes to see if it were working. (I assume it would refresh this?).

thanks for the help.
0
 

Author Comment

by:flynny
ID: 39888757
Just to add I have tried adding a simple hardcoded string to the variables passed;

 data: { "username" : "TEST" },

Open in new window


but I am still getting the same 200 error.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 19

Expert Comment

by:Melih SARICA
ID: 39889083
try to set a variable outside the blockk and then set
 data: variable
0
 

Author Comment

by:flynny
ID: 39889717
Still get the error with this code.

$('#<%=UsernameTextbox.ClientID%>').blur(function () {

            var test = "this is a test";

            $(function () {
                $.ajax({
                    type: "POST",
                    url: "default.aspx/CheckUsername",
                    data: test,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data) {
                            alert('username available');
                        }
                        else {
                            alert('Username already exist');
                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                });
            });
        });

Open in new window

0
 
LVL 19

Accepted Solution

by:
Melih SARICA earned 500 total points
ID: 39889776
this is what im doing..  example for u..
jscript side :
function GetCatalog(Perno, ServiceSucceeded, ServiceFailed) {
    var Year = $("#MainContent_drpDonemyil").val();
    $.ajax({
        cache: false,
        type: "GET", //GET or POST or PUT or DELETE verb
        url: "/HR/srv/DataService.svc/HR/Catalog/" + Year + "/" + Perno, 
        dataType: "json", 
        success: function (data) {
            ServiceSucceeded($.parseJSON(data));
        },

        error: function (jqXHR, textStatus, errorThrown) {
            if (ServiceFailed == null) {
                Showerror(jqXHR, textStatus, errorThrown);
            } else {
                ServiceFailed(jqXHR, textStatus, errorThrown);
            }
        }
    });
}

Open in new window


ServiceSide
 [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "HR/Catalog/{Year}/{Perno}")]
    public string GetCatalog(string Year, string Perno)
    {
        IKSapService.WebService_IK_PDSoapClient clt = new IKSapService.WebService_IK_PDSoapClient();
        IKSapService.ZHR_PD_KAT_ORG req = new IKSapService.ZHR_PD_KAT_ORG();
        IKSapService.ZHR_PD_KAT_ORGResponse resp = new IKSapService.ZHR_PD_KAT_ORGResponse();
        IKSapService.BAPIQUALI_DIR[] cat = { };
        IKSapService.ZHR_PD_OBJEC[] org = { };

        req.GV_PERNR = Perno;
        req.DEG_B = Year + "0101";
        req.DEG_S = Year + "1231";

        req.GT_KATALOG = cat;

        resp = clt.ZHR_PD_KAT_ORG(req);
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(resp.GT_KATALOG);
        return json;
    }

Open in new window


I send data to the webmethod as GET so i send parameters in URL
0
 

Author Comment

by:flynny
ID: 39889934
After adding the following to my web.config (from googling around for solutions) I now am getting a 500 error
 
<httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>

Open in new window

0
 

Author Comment

by:flynny
ID: 39889975
Thanks for all your help

by adding static to the webmethod it now finds it

http://www.stereoplex.com/blog/asp-net-ajax-and-unknown-web-method
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now