Solved

Jquery AJAX and ASP.NET WebMethod

Posted on 2014-02-26
10
1,534 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
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…

707 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

15 Experts available now in Live!

Get 1:1 Help Now