10

I want to call a webservice from javascript.

This is my 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);
    }

My ServiceGetStock.asmx 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;
        }
    }

I got the error message:

POST http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500 (Internal Server Error)

[UPDATE]

I forgot to mention that I added in webconfig of project(with webservice) because I got the error:

XMLHttpRequest cannot load http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:11300' is therefore not allowed access.

  <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Origin" value="*" />
              <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
  </httpProtocol>
POIR
  • 3,110
  • 9
  • 32
  • 48
  • What is the method signature for your `GetStock` – Habib Jan 22 '14 at 14:39
  • Use Fiddler (fiddler2.com) to emulate the `POST` request (using the Composer tab) and take a look at your response - this will tell you specifically the detailed error message you're actually receiving. – Mike Marks Jan 22 '14 at 14:41
  • 500 is a server-side error. Have you debugged the server-side code? Also, `"{id='1'}"` isn't valid json, and `id` != `variant_id`. I'd imagine that matters. – Jason P Jan 22 '14 at 14:42
  • Try `{"variant_id":"1"}` – Mike Marks Jan 22 '14 at 14:42
  • Ok. I changed id into variant_id. It was my mistake. But I got the same error. – POIR Jan 22 '14 at 14:44
  • And you can always attach your Visual Studio debugger to your running process, so when you hit the AJAX call, if you place a breakpoint inside your web method, it *SHOULD* hit. If it doesn't, then there's likely something off about how you're passing in the variable `variant_id`. – Mike Marks Jan 22 '14 at 14:44
  • Again, your data string is not valid json. Try `data: JSON.stringify({variant_id: 1})` – Jason P Jan 22 '14 at 14:46
  • @Otix, one more thing, is the web service on the same server as your website that's making the AJAX call (I'm assuming it is)? – Mike Marks Jan 22 '14 at 14:46
  • My method is correct. But I cannot debug the function GetStock because my webservice is online.(http://www.mywebsite.com/ServiceGetStock.aspx) – POIR Jan 22 '14 at 14:47
  • I think you'll also have a problem if `variant.Stock.ToString()` doesn't generate json (which it probably shouldn't). – Jason P Jan 22 '14 at 14:47
  • I'm telling you, use Fiddler. Fiddler is great. I've ran into similar problems like this and Fiddler tells you EVERYTHING about the HTTP response/errors that come about as a result of a POST/PUT/GET/etc. – Mike Marks Jan 22 '14 at 14:50
  • I'm pretty sure that my webservice is correct. One hour ago I tried to connect with C# and I succeed. – POIR Jan 22 '14 at 14:52
  • @Otix try adding `[ScriptMethod (ResponseFormat = ResponseFormat.Json)]` to your web-method – RononDex Jan 22 '14 at 15:49

2 Answers2

15

Ok guys. I found the problem. When an ASMX file is created, you must read all comments lines. To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

 //[System.Web.Script.Services.ScriptService]

So the GetStock function is:

  [WebMethod]
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetStock(string variant_id)
    {
        SendEmail.SendErrorMail("in"+ variant_id);

        try
        {

            ProductVariant variant = ProductVariantManager.GetProductVariantByID(Convert.ToInt32(variant_id));

            return variant.Stock.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

and the Ajax code is:

   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);
    }

Problem solved! Thanks all for tips.......

Kandarp Vyas
  • 420
  • 6
  • 15
POIR
  • 3,110
  • 9
  • 32
  • 48
  • Going directly to this: `http://myserver:123/WServ/EDt.asmx/HelloWorld` displays the xml. But when I do the above I already get a `0 error`. Any idea why? – Si8 Jan 19 '17 at 21:22
  • @Si8 what error do you get? Show us the error message. – POIR Jan 20 '17 at 08:52
  • Here is my question: http://stackoverflow.com/questions/41752213/why-is-asmx-giving-an-error-when-pulling-data-from-client-script – Si8 Jan 20 '17 at 10:59
  • Do you have to use absolute url? Relative link is not working out for you? – FrenkyB Jul 23 '20 at 09:33
0

use dataType: "jsonp", instead of dataType: "json", jsonp is for cross domian webservice. hope it will help.