Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 608
Sharique Avatar asked Jan 26 '11 18:01

Sharique


2 Answers

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);
    }
})
like image 52
used2could Avatar answered Oct 28 '22 01:10

used2could


I'd recommend adding the [ScriptService] attribute to your Tasks.asmx class so it will accept and respond in JSON instead of XML. Your client code looks good, but you'll want to take a look at "data.d" instead of "data" in your success handler.

like image 43
John Hann Avatar answered Oct 28 '22 02:10

John Hann