2

I'm developing on asp.net webforms and can't solve an issue while making an ajax call from client side. I got the client side script:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
                $.ajax({
                    type: "GET",
                    url: "Default.aspx/getnewmails",
                    data: {},
                    dataType: "html",
                    success: function (str)
                    {
                        $("#div2").html(str);
                    }
                });
        });
    </script>

and Server side method which return html in string var in Default.aspx.cs:

   [WebMethod]
    public static string getnewmails()
    {

        string URI = "https://somewebsite.com/GetEmails.aspx";
        WebClient webClient = new WebClient();
        System.Collections.Specialized.NameValueCollection formData = new System.Collections.Specialized.NameValueCollection();
        try
        {
            formData["uname"] = "john.g";
            formData["upass"] = "12345";
            byte[] responseBytes = webClient.UploadValues(URI, "POST", formData);
            string Result = Encoding.UTF8.GetString(responseBytes);
            return Result;
        }
        catch
        {
            return "";
        }

    }

For some reason when making the ajax call I'm getting the html of same page of Default.aspx and not the Html I expect to get from the getnewmails method... Furthermore, when placing a break point in the server side method it doesn't get hit.

Thanks for the assistance

Nir-Z
  • 819
  • 1
  • 13
  • 31

1 Answers1

1

I have update your code and it works for me.

Updated Code:

$.ajax({
            type: "POST",
            url: "Default.aspx/getnewmails",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("#div2").html(data.d);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $("#div2").html('error: ' + xhr.status + ' ' + thrownError);
            }
        });
Keval Gangani
  • 1,326
  • 2
  • 14
  • 28
  • Thanks, now it works using POST. When I change the type to GET it doesn't work? Why is that? – Nir-Z Mar 16 '15 at 06:47
  • 1
    For security reasons, ASP.Net AJAX page methods only support POST requests. [Reference Link](http://stackoverflow.com/questions/21382917/jquery-ajax-get-method-with-parameter-is-not-working-in-asp-net) – Keval Gangani Mar 16 '15 at 14:45
  • hi keval, i have ajax call which is working fine in local but not in deployed code why? i am using same as ur code – stpdevi Jun 01 '16 at 13:20
  • @stpdevi Did you changed `url` parameter? – Keval Gangani Jun 01 '16 at 14:16