Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Jquery AJAX and ASP.NET WebMethod

Posted on 2014-02-26
10
Medium Priority
?
1,609 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Amazon Web Services EC2 Cheat Sheet

AWS EC2 is a core part of AWS’s cloud platform, allowing users to spin up virtual machines for a variety of tasks; however, EC2’s offerings can be overwhelming. Learn the basics with our new AWS cheat sheet – this time on EC2!

 

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

Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
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…
Suggested Courses

664 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