Search code examples
jquerywcf-data-services

Consume .NET DataService with jQuery


I've had some ADO.NET data services running for awhile and would now like to consume them from a web client via jQuery. When I try to do the following, the error handler is always called:

$.ajax(
    {
        type: "GET",
        url: "Service.svc/Customers()",
        contentType: "application/atom+xml;type=feed;charset=utf-8",  
        dataType: "xml",
        xhrFields: { withCredentials: true },
        error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.response + textStatus + errorThrown); },
        success: function (xml) { alert(xml); }
    }
);

Watching fiddler, the data is correctly returned in XML format but the error handler is always called. Can jQuery not parse application/atom+xml feed responses?


Solution

  • Here is an Ajax Call for JavaScript

    $.ajax({
        url: "Login.aspx/Logout",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (o) {
            window.location.href = "Login.aspx";
        },
        error: function (o) {
            logoutSession();
        }
    });
    

    The server-side method on any aspx page.

    [WebMethod]
    public static string Logout()
    {
        HttpContext.Current.Session["User"] = null;
        return "Success";
    }
    

    When Calling a wsdl service

    $.ajax({
        url: "Service.svc/Customers", 
        type: "POST",
        dataType: "xml", 
        data: soapMessage, 
        processData: false,
        contentType: "text/xml; charset=\"utf-8\"",
        success: function (xml) { alert(xml); }, 
        error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.response + textStatus + errorThrown); }
    });
    

    The soapMessage variable will contain code which looks something like this:

    var soapMessage =
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">\
    <soap:Body> \
    <SaveProduct xmlns="http://sh.inobido.com/"> \
    <productID>' + productID + '</productID> \
    <productName>' + productName + '</productName> \
    <manufactureDate>' + manufactureDate + '</manufactureDate> \
    </SaveProduct> \
    </soap:Body> \
    </soap:Envelope>';
    

    source http://openlandscape.net/2009/09/25/call-soap-xm-web-services-with-jquery-ajax/

    The above source gives you step by step instructions how to, If the source does not work, Google "how to do soap calls from ajax", there will be multiple usable links to this exact query