Barış Velioğlu
Barış Velioğlu

Reputation: 5827

Jquery ajax call to a method of a aspx page

I have two aspx page on my application. From the first one, lets say default.aspx, I have one button and one textbox. When I click the button I do an ajax call to the checkname.aspx as below

            function docheck() {

            var un = $('#username').val();


            $.ajax({

                url: "checkname.aspx",
                data: { name: un, method: 'checkname' },
                dataType: 'script',
                success: function (val) {

                    if (val == "No")
                        alert("not valid");
                    else
                        alert("valid!");

                }

            });
        }

From checkname.aspx page I do the operations like below but it response is also adding the checkname.aspx page's html to the response so the success message of ajax call doesnt became what I wanted. How do I send just what the CheckName method send.

checkname.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {


  NameValueCollection queries = HttpUtility.ParseQueryString(Request.QueryString.ToString());

    if(queries["method"] == "checkname")
        this.CheckName(queries["name"]);
}

protected void CheckName(string Name)
{
    if (Name == "ryu")
    {
        HttpContext.Current.Response.Write("No");
        return;
    }

    HttpContext.Current.Response.Write("Yes");
}

Thanks in advance,

Upvotes: 0

Views: 1354

Answers (2)

Bartosz
Bartosz

Reputation: 3358

Call HttpContext.Current.Response.End(); to end processing your aspx request, otherwise, all stuff after that call in Page_Load gets processed normally, thus you've got the results you've described.

But in general, follow the advices given by other people here, and work with your AJAX requests in different way.

Upvotes: 1

Jonas Høgh
Jonas Høgh

Reputation: 10884

Note that this is a very clunky way to work with Ajax requests, as the method has nothing to do with the page it is on. (The entire control hierarchy of the page is meaningless in an Ajax context).

I would suggest that you look into using WCF instead, see e.g. this tutorial

Upvotes: 2

Related Questions