1

I am working on asp.net web forms application. I am trying to make an ajax call to a web method in codebehind, but instead of returning the result, it returns the whole html page.

I am calling it on button click

 <input type="button" id="btnCallAPIFromClient" class="btn btn-success" value="Call API from Client"/>

My js script is:

$(document).ready(function() {
    //PageMethods.set_path(PageMethods.get_path() + '.aspx');
    $('#btnCallAPIFromClient').click(function() {
        alert('here');
        $.ajax({
            url: '/login/GetAccessToken',
            type: "POST",
            dataType: 'html',
            success: function(response) {
                alert(response);
                debugger;
                sessionStorage.setItem("accessToken", response.access_token);
                alert(response.access_token);
            },
            // Display errors if any in the Bootstrap alert <div>
            error: function(jqXHR) {
                alert(jqXHR.responseText);
            }
        });
    });
});

webmethod is:

   [WebMethod]
        public static string GetAccessToken()
        {
           return "abc";
        }
4
  • 1
    Notice dataType: 'html', try once with dataType: "text",
    – Satpal
    Jan 13, 2017 at 9:56
  • 1
    Also add contentType: "application/json; charset=utf-8",dataType: "json" Jan 13, 2017 at 9:57
  • For someone really sure ajax structure forming in right way who could doubt ScriptModule not loading well. I have answer here.
    – 劉鎮瑲
    Jul 29, 2019 at 8:51
  • My suggestion to anyone having these types of problems: please double check the routing.
    – QMaster
    Jun 24, 2023 at 23:39

1 Answer 1

0

This is because you have set the datatype as html. Change the datatype to text as follows:

dataType: 'text'

And also in the success function change this line

sessionStorage.setItem("accessToken", response.access_token);

To

sessionStorage.setItem("accessToken", response);

Because you are not receiving data in json format. So this will be invalid.

4
  • @AsifHameed, have you tried what i've mentioned in comment ? Jan 13, 2017 at 10:09
  • yes, I see this in the network tab of chrome: {Message: "Authentication failed.", StackTrace: null,…} ExceptionType : "System.InvalidOperationException" Message : "Authentication failed." StackTrace : null Jan 13, 2017 at 10:10
  • Please do have a look ---> link. Maybe this is what you are struggling at Jan 13, 2017 at 10:20
  • Thanks Prashant Pokhriyal Jan 13, 2017 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.