0

I have the following problem I am trying to connect a HTML page with a asmx service, using jquery. The service is in my local IIS, and I have configured it for allow cross-domain request: This is my service code:

[WebService(Namespace = "http://myservices.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class Test : WebService
{   
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public Employee TestMethod()
    {
        return new Employee { Id = 1, Name = "John"};
    }
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

This is my web.config service code:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <add name="ScriptHandlerFactory"
           verb="*" path="*.asmx"
           type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
           resourceType="Unspecified" />
    </handlers>
  </system.webServer>
</configuration>

So, with that I can call to service method from anywhere (different domains) using this url

http://localhost/WsTest/Test.asmx/TestMethod

But, the response is in xml, why? ... I don't know what I need

<Employee xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://myservices.org/">
    <Id>1</Id>
    <Name>John</Name>
</Employee>

That is my first question.

Second, When I try to get the service response using ajax with the following code:

$.ajax({
    url: "http://localhost/WsTest/Test.asmx/TestMethod",
    beforeSend: function () {},
    data: {},
    contentType: "application/json; charset=utf-8",
    type: "POST",
    dataType: "jsonp",
    processData: false,
    cache: false,
    success: function(data) {
        alert(data)
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("Retrieve Failed (AJAX Error): " + jqXHR.statusText + " | " + textStatus + " | " + errorThrown);
    }               
});

I get the following response:

TestMethod?callback=jQuery220045970173459500074_1454084649739&[object Object]&_=1454084649740:1

Uncaught SyntaxError: Unexpected token <

Retrieve Failed (AJAX Error): load | parsererror | Error: jQuery220045970173459500074_1454084649739 was not called

I have read several answers about this question, but i cannot find the appropriate answer for my problem.

Thanks in advance!

1 Answers1

0

I think you are not properly serializing the response before sending it back to the client.

You have to make your class serializable into a Json string. To do that follow the instructions provided in the following MSDN link:

How to: Serialize and Deserialize JSON Data

Then, you should change your web method to return a String value, and just before returning the response to the client, do the serialization trick, something like this:

var objectSerializer = new JavascriptSerializer();
//serialization  
return objectSerializer.Serialize(data); //this will return a Json string

For more details about the JavascriptSerializer class check out the following link:

JavaScriptSerializer Class

And about your error, it is because your response is returning in XML format (the standard SOAP response) thus the javascript code you are using is expecting a Json format. The trick is to simply return a Json string.

The other option you have is to use WCF instead of ASMX, but that is another path you can check out here:

How do I return clean JSON from a WCF Service?

Beware about the security risks involved in exposing your service like that. Use unique ids or other mechanisms to secure your web service invocations from Javascript.

Community
  • 1
  • 1
lidermin
  • 2,782
  • 11
  • 43
  • 48