0

I am using jquery ajax to send JSON data to a webservice.

My JS code is-

function addToCart(id) 
    {
        $.ajax({
            type: "POST",
            url: "WebService1.asmx/HelloWorld",
            contentType: "application/json; charset=utf-8",
            data: "{id:"+id+"}",
            dataType: "json",
            success: function (data) {
                //alert(data.d);
            }
        });
    }

and WebService1.asmx is -

 [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
//[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public static int HelloWorld(int id)
    {
        return id;
    }
}

If I call the js function as addToCart(8), the content of post tab in firebug is- {id:8}

and the response is- {"d":"Hello World"}

Now my questions are-

  1. how to get the id (that is 8 in this case) in my Web Service so that I can store it in my DB.
  2. why it always gives the response as d:Hello World, where it is defined?
  3. how to send the proper response again to the js that I wanna show in alert box in success function of ajax call(assume I want to show 8 again in alert, what do I need to write in Web Service and alert box).
  4. and what is about tempuri.org, do I need to change it in my case?
Aditya Vijay
  • 231
  • 2
  • 13
  • Hi there, potentially [this](http://stackoverflow.com/questions/211348/how-to-let-an-asmx-file-output-json) question can help you. The accepted answer to the question links to [this](http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/) article, which seems to describe your use case, but I think it's worth reading the full SO question as well. – nkvu Apr 10 '13 at 21:24
  • I would highly suggest moving towards Asp.Net WebApi or at least an MVC implementation - it is much easier, and this is considered an old method in many circles. – naspinski Apr 10 '13 at 22:13
  • @nkvu: The code I wrote above is alright. I just need to rebuild the solution every time to run on browser instead of doing refresh, I think this is because I am using **CodeFile** attribute in Page directive instead of **CodeBehind**. Does it matter?? – Aditya Vijay Apr 13 '13 at 11:22

0 Answers0