title: Calling ASMX Web Service from Javascript
body: <p>I want to call a webservice from javascript.</p>
  
  <p>This is my code:</p>
  
  <pre><code>    var method="GetStock";
      var url = "http://www.mywebsite.ro/ServiceGetStock.asmx";
      $.ajax({
          type: "POST",
          url: url + "/GetStock",
          data: "{variant_id='1'}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: OnSuccessCall,
          error: OnErrorCall
      });
  
      function OnSuccessCall(response) {
          alert(response.d);
      }
  
  
      function OnErrorCall(response) {
          alert(response.status + " " + response.statusText);
      }
  </code></pre>
  
  <p>My ServiceGetStock.asmx code:</p>
  
  <pre><code> [WebMethod]
      public string GetStock(int variant_id)
      {
          try
          {
  
              ProductVariant variant = ProductVariantManager.GetProductVariantByID(variant_id);
  
              return variant.Stock.ToString();
          }
          catch (Exception ex)
          {
              return ex.Message;
          }
      }
  </code></pre>
  
  <p>I got the error message:</p>
  
  <p><em>POST <a href="http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock" rel="noreferrer">http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock</a> 500 (Internal Server Error)</em> </p>
  
  <p>[UPDATE]</p>
  
  <p>I forgot to mention that I added in webconfig of project(with webservice) because I got the error:</p>
  
  <p><em>XMLHttpRequest cannot load <a href="http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld" rel="noreferrer">http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:11300' is therefore not allowed access.</em> </p>
  
  <pre><code>  &lt;httpProtocol&gt;
            &lt;customHeaders&gt;
                &lt;add name="Access-Control-Allow-Origin" value="*" /&gt;
                &lt;add name="Access-Control-Allow-Headers" value="Content-Type" /&gt;
            &lt;/customHeaders&gt;
    &lt;/httpProtocol&gt;
  </code></pre>