Search code examples
asp.netjqueryasmx

calling asmx service using jquery ajax asp.net 4.0


I'm trying to call a sample asmx service using jquery, here is the jquery code

$.ajax({
            type: "POST",
            url: "/Services/Tasks.asmx/HelloWorld",
            data: "{}",
            dataType: "json",
            contentType: "application/xml; charset=utf-8",
            success: function (data) {                   
                alert(data);                    
            }
        });

This is not showing any message,code is in asp.net 4.0, Am I missing any thing?

Edit - I changed the dataType to xml, now success function is working it return following xml

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

I'm using following code to parse xml data and it is showing null in alert

success: function (data) {
    edata = $(data).find("string").html();
    alert(data);
}

Solution

  • I believe it's because you have the dataType: "json" and it's expecting the response content-type to be the same but XML is being returned. I bet the complete event is being raised but not success.

    try

    $.ajax({
                type: "POST",
                url: "/Services/Tasks.asmx/HelloWorld",
                data: "{}",
                dataType: "json",
                contentType: "application/xml; charset=utf-8",
                success: function (data) {                   
                    alert(data);                    
                },
                complete: function (data) {                   
                    alert(data);                    
                }
            });
    

    UPDATE

    I think it's because you're using .html(), you need to use text(). Also i don't know if you meant to do it or not but you have data in your alert, i'm assuming you meant to use edata. The following worked for me:

    jQuery.ajax({
        type: "POST",
        url: "/yourURL",
        dataType: "xml",
        data: "{}",
        contentType: "application/xml; charset=utf-8",
        success: function(data) {
            edata = $(data).find("string").text();
            alert(edata);
        }
    })