Solved

Jquery AJAX and ASP.NET WebMethod

Posted on 2014-02-26
10
1,571 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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 

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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
JQuery on multiple lines 3 47
ComboBox to String Not Working 5 43
CSS (jquiry mobile) question 3 34
Add Promise to Existing Code 6 30
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
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…

739 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