Solved

Jquery AJAX and ASP.NET WebMethod

Posted on 2014-02-26
10
1,555 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

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
 
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

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

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

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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…

809 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