title: Connect javascript with asp.net
body: <p>I'm with troubles to connect javascript with asp.net webforms method via ajax and json.</p>
  
  <p>I have the javascript in one folder and page.aspx in the other for example:
  - Account/createUser.aspx
  - Script/actions/createuser.js</p>
  
  <p>I already tried many things, for example, use before the method [Webmethod], in the ajax action change many things, but nothing works. In mostly of tentatives the google chrome give the error:</p>
  
  <blockquote>
    <p>POST .../Account/createUser.aspx/CheckUserName 401 (Unauthorized)</p>
  </blockquote>
  
  <p>If I remove in javascript lines like: "dataType: json" and "contentType: application/json; charset=utf-8" the error disappears and enter on "complete" line...</p>
  
  <p>I need instructions to resolve this problem... I search a lot of posts, follow many tutorials and nothing means work. 
  For example: change my webconfig to accept any users, my routeconfig.cs...</p>
  
  <p>Is something faling? What? Do I need to declare something to use json?</p>
  
  <p>Javascript:</p>
  
  <pre><code>$("#USUserName").change(function () {
      alert($("#USUserName").val());
      $.ajax({
          type: "POST",
          url: "createUser.aspx/CheckUserName",
          data: '{username: "' + $("#USUserName").val() + '" }',
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          complete: function (jsondata, stat) {
              if (stat == "success") {
                  var response = JSON.parse(jsondata.responseText).d;
                  alert((response));
              }
          },
          error: function (xhr, ajaxOptions, thrownError) {
              alert();
          }
      });
  </code></pre>
  
  <p>aspx.cs code:</p>
  
  <pre><code>[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
      public string CheckUserName(string username)
      {
          var existUser = context.user.Where(us =&gt; ((us.username).Equals(username))).Count();
          string returnValue = string.Empty;
          if (existUser.Equals(0))
          {
              returnValue = "test- yes!";
  
          }
          else
              returnValue = "test- no!";
          return returnValue;
      }
  </code></pre>