Click here to Skip to main content
Click here to Skip to main content

Accessing Remote ASP.NET Web Services Using JSONP

By , 13 Oct 2009
 

The problem:

You cannot call remote ASP.NET Web Service methods from a JavaScript, AJAX client.

Example:

You have a Web Service at this address: http://a.com/service.asmx and you've configured the service to work with AJAX clients:

[WebService
(Namespace = "http://www.hyzonia.com/gametypes/PopNDropLikeGame/WS2")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class GameService : System.Web.Services.WebService
{
    [WebMethod(EnableSession = true)]
    public GameSessionResponse CreateGameSession(Guid questId)
    {
...
    }
}

And it works fine when you call its methods from a web page that is in this address: http://a.com/page.htm:

$.ajax({
        type: "POST",
        url: "GameService.asmx/CreateGameSession",
        data: "{questId: '" + questId + "'}",
        cache: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            Game._onSessionGot(response.d);
        }
    });

But the very same client-side code doesn’t work from this address: http://b.clom/page.htm.

The problem in depth:

At first, it is a silly problem, for me it is an overprotection. After all, Web Services are meant to be called by remote clients. The fact that browsers block access to Web Services by AJAX calls is clearly contrary to the purpose of Web Services.

Interestingly, browser extensions like Flash and Silverlight also, by default, block remote Web Services, but they provide a workaround. Unfortunately, no browser by date supports this work around for XMLHttpRequests. This "security measure" seems odder when we notice that it is perfectly correct to import a JavaScript code snippet from another domain using a script tag:

<script
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
  type="text/javascript">
</script>

The solution:

As it was said, Flash and Silverlight both support remote calls. You just need a client access policy file to be hosted at the root of a.com (http://a.com/clientaccesspolicy.xml):

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

This file allows remote calls to be made from any other domain.

But in many situations, we want to call the Web Service methods directly from AJAX clients. This need was the cause of the development of JSONP (JSON with padding) protocol. As it was discussed, it is correct to have a <script> element that loads a script from another domain. On the other hand, you may know that it is possible to load scripts dynamically by a simple JavaScript trick (writing <script> tags) or using this jQuery plug in. Now the bulbs are flickering! The solution is to access the JSON Web Service by the src attribute of a <script> element. This is the whole idea behind JSONP.

But there are a couple of problems needed to be solved for ASP.NET ASMX Web Services before we can use them in a JSONP scenario.

  1. ASP.NET Web Services by default only accept POST requests; a <script src=""> element, produces a GET request.
  2. The result of the web method call must conform to JSONP, and as you can guess, ASP.NET 3.5 by default doesn’t support it.

The solution to the first problem may seem trivial, we can easily enable GET calls to web methods using the [ScriptMethod(UseHttpGet = true)] attribute. The immediate problem is that when we mark a web method by this attribute, it can only be called by GET requests. And remember, other clients (actually anything other than JSONP clients) are supposed to communicate with the web service by POST requests. I usually end up inheriting from the original Web Service and marking web methods by the [ScriptMethod(UseHttpGet = true)] attribute in the derived class. Therefore, I will have two ASMX Web Services, one using the original class (expecting POST requests) and the other using the derived class (expecting GET requests).

[WebMethod(), ScriptMethod(UseHttpGet = true)]
public override GameSessionResponse CreateGameSession(Guid questId)
{
   return base.CreateGameSession(questId);
}

Note you may need to add this code snippet in web.config:

<system.web>
 <webServices>
   <protocols>
     <add name="HttpGet"/>
   </protocols>
 </webServices></system.web>

There's another problem to be addressed in the client side. The client should call the web method using the correct URL (it has to pass the correct query string that could be deserialized back to .NET objects in the server side). In case of POST requests, I'm used to JSON2 library to post data to ASP.NET ASMX Web Services. JQuery $.AJAX method (when it is configured to use JSONP, using dataType: "jsonp") creates query string parameters for the data objects it receives. But the result is not usable for ASMX Web Services.

Luckily, there's a ready to use JQuery plug-in (jMsAjax) that has the required algorithms for serializing a JavaScript object into a query string that can be parsed by ASP.NET Web Services.

Using the plug-in, I created this function to serialize JavaScript objects into query strings:

$.jmsajaxurl = function(options) {
    var url = options.url;
    url += "/" + options.method;
    if (options.data) {
       var data = ""; for (var i in options.data) {
       if (data != "")
         data += "&"; data += i + "=" + 
                 msJSON.stringify(options.data[i]);
       }
       url += "?" + data; data = null; options.data = "{}";
   }
   return url;
};

You will need jMsAjax for this code snippet to work.

Finally, this is a sample of a client side code using JQuery that calls an ASMX Web Service using JSONP:

var url = $.jmsajaxurl({
    url: "http://hiddenobjects.hyzonia.com/services/GameService3.asmx",
    method: "Login",
    data: { email: "myemail@mydomain.com", password: "mypassword" }
});

$.ajax({
    cache: false,
    dataType: "jsonp",
    success: function(d) { console.log(d); },
    url: url + "&format=json"
});

Or equivalently:

$.getJSON(url + "&callback=?&format=json", function(data) {
    console.log(data);
});

When you call an ASP.NET Web Service method (that is configured to receive GET requests) using a code similar to the above, it returns in XML. The problem is that the Web Service expects to receive a request that has a content type of "application/json; charset=utf-8" and the <script> element simply doesn't add this content type to the request. There's a little thing we can do at the client side. The easiest way to resolve this problem is to use an HTTP module. The HTTP module should add this content type to the requests before they are processed by the Web Service handler.

On the other hand, a JSONP client expects that the Web Service returns the call by a string like this:

nameOfACallBackFunction(JSON_OBJECT_WEB_METHOD_RETURNED)

nameOfACallBackFunction must be given to the server by a parameter in the query string. Different JSONP compatible Web Services use different names for this parameter, but usually it is named 'callback'. At least, this is what $.ajax() automatically adds to the request in JSONP mode.

We have to modify the response stream that the server is returning. Luckily, in ASP.NET, it is easy to apply a filter to the response.

I slightly modified this HTTP module that I originally grabbed from a post in elegantcode.com, to improve its performance:

public class JsonHttpModule : IHttpModule
{
    private const string JSON_CONTENT_TYPE = 
            "application/json; charset=utf-8";

    public void Dispose()
    {
    }

    public void Init(HttpApplication app)
    {
        app.BeginRequest += OnBeginRequest;
        app.ReleaseRequestState += OnReleaseRequestState;
    }

    bool _Apply(HttpRequest request)
    {
        if (!request.Url.AbsolutePath.Contains(".asmx")) return false;
        if ("json" != request.QueryString.Get("format")) return false;
        return true;
    }

    public void OnBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;

        if (!_Apply(app.Context.Request)) return;
        
        // correct content type of request
        if (string.IsNullOrEmpty(app.Context.Request.ContentType))
        {
            app.Context.Request.ContentType = JSON_CONTENT_TYPE;
        }
    }

    public void OnReleaseRequestState(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;

        if (!_Apply(app.Context.Request)) return;

        // apply response filter to conform to JSONP
        app.Context.Response.Filter = 
            new JsonResponseFilter(app.Context.Response.Filter, app.Context);
    }
}

public class JsonResponseFilter : Stream
{
    private readonly Stream _responseStream;
    private HttpContext _context;

    public JsonResponseFilter(Stream responseStream, HttpContext context)
    {
        _responseStream = responseStream;
        _context = context;
    }

    //...

    public override void Write(byte[] buffer, int offset, int count)
    {
        var b1 = Encoding.UTF8.GetBytes(
          _context.Request.Params["callback"] + "(");
        _responseStream.Write(b1, 0, b1.Length);
        _responseStream.Write(buffer, offset, count);
        var b2 = Encoding.UTF8.GetBytes(");");
        _responseStream.Write(b2, 0, b2.Length);
    }

    //...
}

This HTTP module will be applied to each request to an .asmx file that has a format=json in its query string. Note that you have to update web.config:

<system.web><httpModules><add name="JSONAsmx" type="JsonHttpModule, App_Code"/>
  </httpModules>
</system.web>

for IIS6, and:

<system.webServer>
  <modules><add name="JSONAsmx" type="JsonHttpModule, App_Code"/>
  </modules></system.webServer>

for IIS7.

Now to test it, let's open the Web Service in a browser window; in my example, http://hiddenobjects.hyzonia.com/services/GameService3.asmx/Login?email=e@e.com&password=p should return in XML, and http://hiddenobjects.hyzonia.com/services/GameService3.asmx/Login?email="e@e.com"&password="p"&format=json&callback=myCallBackFunc will return:

myCallBackFunc({"d":{"__type":"HLoginResponse",
   "isSuccessful":false,"error":false,"authSessionId":null,
   "nickName":null,"score":0}});

Don't worry about myCallBackFunc, JQuery nicely manages it so that the whole business is behind the scene and you can use the $.ajax success callback the very same way you use it for a normal AJAX call.

We should note that JSONP has its own problems, especially… yes... in IE! All versions of Internet Explorer have a 2083 character limit for the URL of a request. It means that you cannot send large data in GET requests to the server. Sometimes this limitation leaves us with no choice but to use Flash or create a proxy to the remote Web Service in the local domain.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Homam Hosseini
Web Developer
United Arab Emirates United Arab Emirates
Member
I love messing around with JavaScript, my discovery of the power of JavaScript was the biggest discovery since the time I found out I like astronomy. I spent most of my life shooting heavenly bodies, studying physics, organizing or just being a nice member of amateur astronomy groups and writing about astronomy.
 
I believe in fast and agile development styles, things just change for a small company before almost any design could be finalized. The programs that I create evolve. An evolved program works better and better by time, but finally nobody knows how!
 
Seriously, I’m a software architect with wild ideas. I enjoy working on large distributed systems, anything from remotely controlling a telescope to a network of games distributed all over the internet.
 
Here is the latter one, Hyzonia; I invested a good amount of time on designing and developing it. You might enjoy it if you want to spice up your website with some games or if you’re looking for a good reason to develop a casual game.
 
Here's my blog.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionPLEASE HELP ASAP !!!membertestho@yahoo.ocm2 Sep '12 - 0:20 
Really thanks for your great article.
 
I am Getting small problem when i am using your code.
 
I'm using a JSONP ajax call to load some content from a different domain, and all this stuff is executed if the user causes a "mouseover" on a button.
 
Is there a way to handle that exception?
 
The raised exception is like this (according to Firebug): jQuery16102234208755205157_1308941669256 is not a function
 
And the exception's internal structure is like this: jQuery16102234208755205157_1308941669256({... my json data from a different domain....})
 
Please let me know, if you have any solution or suggestion.
AnswerRe: PLEASE HELP ASAP !!!memberHomam Hosseini2 Sep '12 - 0:32 
Well, I will need more info to help. A fiddle maybe.
GeneralRe: PLEASE HELP ASAP !!!membertestho@yahoo.ocm2 Sep '12 - 2:28 
OK,
 
(1) I included Javacript file in our project which is provide by you in your demo(WS.js and jMsAjax.js).
(2)Also Done changes in config file.
(3) I created a JSONP function according to article.
function CityByCountry() {
 
    var key = 0;
    var countryID = jQuery('#DropDownCountry').val();
    var url = $.jmsajaxurl({
        url: "http://www.mysite.com/Communication.asmx",
        method: "GetCityData",
        data: { WLChannelID: parseInt(key), WLCountryID: parseInt(countryID) }
    });
 
    $.ajax({
        cache: false,
        dataType: "jsonp",
        success: function (d) {
            var result = JSON.parse(msg.d);
            if (result != null) {
alert(result);
            }
            
        },
        url: url + "&format=json"
    });
}
 
This function call by other server www.abc.com to hit my service which is hosted my server. This function working fine on first two attempt after that i am getting that exception which is posted in my question. when i call again this function after 5-10 minute than again working fine for two - three attempt after that i again getting that exception and i am not able to get my data.
 
So please let me know, what i can do for this.
GeneralRe: PLEASE HELP ASAP !!!membertestho@yahoo.ocm2 Sep '12 - 19:10 
I not able to solve this problem yet :(
AnswerRe: PLEASE HELP ASAP !!!membertestho@yahoo.ocm3 Sep '12 - 3:10 
Hello,
 
I am sorry to say, but it is true, Your Demo Project is not working correctly after deploy on IIS 7.
 
You can check fter deploy on ISS 7 Please click on (cal) button 5-6 times and check fire bug console.
 

The raised exception is like this (according to Firebug): jQuery16102234208755205157_1308941669256 is not a function
QuestionRestfullmemberjoseph_man16 Jul '12 - 3:21 
what about Restfull service?
QuestionMy vote of 5memberhristiyan.dimov28 Feb '12 - 1:12 
Excellent, it works perfect. Thanks for sharing. You should really update the code in the article though with the fix.
GeneralMy vote of 5memberCompufreak45624 Feb '12 - 1:28 
Wow. This article really helped me out. And it was so easy to do using your code snippets!
QuestionMUST UPDATE CODE WITH CORRECTION OF 15:17 14 Apr '10membercardigait28 Oct '11 - 9:16 
Wonderful code but as others stated goes nuts with great chunks of data, incapsulating multiple callback and crashing the request with abstruse error.
 
I lost one day hunting jQuery and... finally i found jQuery innocent.
 
Againt, wonderful library and is (freely) helping me a lot but PLEASE update the code.
 
I would vote 5 for the suggestion, i'll wait for the update
GeneralMy vote of 5membermarcelsnews14 Oct '11 - 4:27 
excellent article. I've face this problem in .net senchatouch. When i read this article i resolved my problem in one hand.
The article is clear and examples are fully functional.
Thank for sharing code Wink | ;)
GeneralRe: My vote of 5membererhan demirci2 Feb '12 - 2:06 
Wink | ;) I am new in senha touch .pls help. can you send webservice solve source code?   my e-mail=demirci.erhan@windowslive.com
GeneralRe: My vote of 5membermarcelsnews2 Feb '12 - 3:06 
Hi i can not send personal email Frown | :-( .
 
But which problem did you face ? On the server side or on the client side ?
l'éternel est mon berger: je ne manquerai de rien.

GeneralRe: My vote of 5membererhan demirci2 Feb '12 - 3:10 
server side. problem is not show data in sencha touch. thanks. help .
GeneralRe: My vote of 5membermarcelsnews2 Feb '12 - 11:43 
OK so if i understand the problem is on the SERVER SIDE:
Questions:
- First of all, Does your server handle Webservices ?
 
- Did you follow your code execution on "debug" mode to see if your server receive the request and compute it correctly ?
 
- If yes, Do your server send reply in JSON format to your client ?
 
- OR Do you have a response from the server, but not correctly formatted ? (that meants if you execute it on your browser you have data in an XML format)
 
- Or you have not been abble yet to setup the JSONP-Module on your server side ?
 
Having your response, i will know how to help ....
l'éternel est mon berger: je ne manquerai de rien.

GeneralRe: My vote of 5membererhan demirci2 Feb '12 - 21:52 
I call w3webservice but not connection
 
my webservice : http://www.w3schools.com/webservices/tempconvert.asmx[^]
 
html file Hmmm | :|
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jMsAjax.js" type="text/javascript"></script>
    <script src="Scripts/WS.js" type="text/javascript"></script>
</head>
<body>
<p>
    <label for="UseJSONP">Use JSONP</label> <input type="checkbox" id="UseJSONP" name="UseJSONP" value="true" />
    <br />
    Surface( <input type="text" id="Celcius" name="Celcius" value="1" /> ) = <span id="Surface"></span>
    <br />
    <button id="Calc" onclick="return false;">Calc</button>
</p>
 
    <script type="text/javascript">
        $(function() {
            $("#Calc").click(function() {
                var jsonp = $("#UseJSONP").attr("checked");
                var service = new WS("http://www.w3schools.com/webservices/tempconvert.asmx",WSDataType.jsonp);
                service.call("CelsiusToFahrenheit", { Celsius: parseFloat($("#Celcius").val()) }, function(surface) {
                    $("#Surface").html(surface);
                });
            });
        });
    </script>
</body>
</html>

GeneralRe: My vote of 5membererhan demirci7 Feb '12 - 3:04 
hi. I not solved calling webservice in sencha touch . pls simple tutorial   :(
GeneralMy vote of 5memberMember 56545114 Apr '11 - 1:56 
Very helpful article. Helped me in cross-domain posting. Trying the GET method!!
Cheers,
Alok
QuestionInvalid JSON Primitive?memberMember 48686422 Dec '10 - 19:44 
I tried implementing this (I'm using VS 2005, jQuery 1.4.2). I'm passing a single string parameter to the WebMethod. The error I'm getting back is saying the value I'm passing in is an invalid JSON primitive.
 
Now, if I change the value of the string from what it is (a 30 character string of alphanumerics) to a string of numbers (e.g. "1234567890"), it will work.
 
Any idea why it seems to think my one parameter that's defined as a string needs to be a number?!?
 
This is the WebMethod's signature:
 
[WebMethod()]
[ScriptMethod(UseHttpGet=true)]
public SomeReturnedObject GetSomeReturnedObject(string inStoreID) {...}
 
The JS call looks like this (modified for public consumption of course):
 
var jsonp_url = sSiteDomain + "/MyService.asmx/GetSomeReturnedObject?callback=?";
var postdata = { inStoreID: sStoreID };
$.getJSON(jsonp_url, postdata, function(data) {...});
 
where "sStoreID" is a string like "asl23k12lasdkalsk23l". jQuery seems to be handling it right (i.e. it'll add "&inStoreID=asl23k12lasdkalsk23l" to the URL and make it a GET) but I get that invalid JSON primitive error.
 
And before you ask, yes, I've tried just removing the "callback=?" and putting in something like "format=jsonp" in the query string for the http filter to catch instead (so jQuery doesn't do anything to it). In other words, just do an ajax GET to:
 
/MyService.asmx/GetSomeReturnedObject?inStoreID=asl23k12lasdkalsk23l&format=jsonp
 
And I still get the invalid primitive error. I'm at a loss here. I'm trying to implement a widget that needs to reside on other people's site and point to ours. Thus jsonp.
 
Any suggestions? Thanks in advance.
 
kn
GeneralProblem with Internet Explorermemberpawel198527 Oct '10 - 2:55 
Hi,
 
First of all, thanks for this useful document, it has been perfect for me. The example and the code work fine when I'm using Firefox and with IE when I'm using a local server but when I try to use a remote server with the IE I always get the same error with the debug in the jquery 1.4.2:
 
Code:
 
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
script.src = s.url;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
 
Error:
Operation invalid.
 
That's all the information that I have and now I want buy a gun or something and destroy microsoft ! hahaha. Please, if anybody knows how to to this, tell what you got it.
 
Regads,
Pawel.
GeneralBug when returning a large amount of JSONmemberjustintoth11 Mar '10 - 16:13 
Thanks for this article, it helped me get really close to solving this nightmare of an issue of x-domain webservice calls in ajax. However, there seems to be a bug within the JsonResponseFilter class if there's a lot of json and it splits up the writing. Check out this json that was generated using this method:
 
"AwayTeam": {
"Id": 353,
"Name": "Hawkeyes",
"Score": 52,
"Record": "(10-21)",
"Won": 0,
"Loss": 0,
"Tie": 0,
"City": "Iowa",
"IsSubscribed": false,
"DivisionName": null,
"Frequency": null);jsonp1268363331412(,
"SportId": 0,
"SportName": null,
"FrequencyCode": 0
},
 
It randomly added in that jsonp bit and it inserts it 6-7 times through my json, which obviously makes everything blow up. Why is it doing this??
GeneralRe: Bug when returning a large amount of JSONmemberjustintoth11 Mar '10 - 16:19 
I see the issue... When the json is large enough, it calls the Write method in JsonResponseFilter multiple times, as it breaks up the json into chunks. Your code is wrapping the jsonp text around whatever Write writes, however since it's breaking it up into chunks, it ends up getting intertwined in the json. I'm not sure how to fix it though...
GeneralRe: Bug when returning a large amount of JSONmemberjustintoth11 Mar '10 - 18:08 
Here's the fix to that bug:
 
StringBuilder _sb = new StringBuilder();
 
public override void Write(byte[] buffer, int offset, int count)
{
string json = System.Text.Encoding.UTF8.GetString(buffer, offset, count);
_sb.Append(json);
 
var endOfFile = new Regex("]");
if (endOfFile.IsMatch(json))
{
string message = _context.Request.Params["callback"] + "(" + _sb.ToString() + ");";
buffer = System.Text.Encoding.UTF8.GetBytes(message);
_responseStream.Write(buffer, 0, buffer.Length);
}
}
GeneralRe: Bug when returning a large amount of JSONmemberrealstrategos3314 Apr '10 - 12:17 
That did not work for me for some reason
the following did however:
        private bool IsStarted { get; set; }
 
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (!IsStarted)
            {
                IsStarted = true;
                var b1 = Encoding.UTF8.GetBytes(_context.Request.Params["callback"] + "(");
                _responseStream.Write(b1, 0, b1.Length);
            }
            _responseStream.Write(buffer, offset, count);
        }
 

        public override void Close()
        {
            var b2 = Encoding.UTF8.GetBytes(");");
            _responseStream.Write(b2, 0, b2.Length);
            _responseStream.Close();
        }
 

GeneralRe: Bug when returning a large amount of JSONmembertompynation855 Mar '12 - 7:32 
None of the solutions above worked for me... I also had to problem that with large amount of data that it stopped working but i just fixed it by adding the following to the web.config:
 
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
 

<pre lang="xml">&lt;system.web.extensions&gt;
    &lt;scripting&gt;
      &lt;webServices&gt;
        &lt;jsonSerialization maxJsonLength=&quot;2147483644&quot;&gt;
        &lt;/jsonSerialization&gt;
      &lt;/webServices&gt;
    &lt;/scripting&gt;
  &lt;/system.web.extensions&gt;</pre>

GeneralRe: Bug when returning a large amount of JSONmemberseph2m14 Sep '12 - 0:46 
Thanks, that solution works for me!
trust urself!

GeneralThere's a problem with the JavaScript code you've provided in this article!memberMehdi Mousavi10 Jan '10 - 22:40 
Hi,
I encountered a weird problem when reading the article. Consider the following JavaScript code you've just mentioned in the article:
 
$.jmsajaxurl = function(options) {
    var url = options.url;
    url += "/" + options.method;
    if (options.data) {
       var data = "";
       for (var i in options.data) {
       if (data != "")
         data += "&"; data += i + "=" + msJSON.stringify(options.data[i]);
       }
       url += "?" + data; data = null; options.data = "{}";
   }
   return url;
};
 
The problem is that data is and will always be an empty string! I believe you need to change the if (data != "") line to if (i != "").
Anyway, I've just modified the script as follows:
 
$.jmsAjaxUrl = function(options) {
    var url = '';
    $.each(options.data, function(name, value) {
        url += (url == '' ? '?' : '&') + name + "=" + msJSON.stringify(value);
    });
 
    options.data = '{}';
 
    url = options.url + '/' + options.method + url;
    return url + '&callback=?&format=json';
};
 
Thank you for your informative article, though.
 
Keep up the good work,
 
Mehdi Mousavi - Software Architect [ http://www.mehdi.biz/blog/ ]

QuestionGreat article, but curiousmemberhasheend29 Oct '09 - 10:23 
Homam,
 
Let me first say that this is a well-written article and very informative. I was wondering if there were any settings modified on the remote server in your example? I'm trying to test the code presented in my local environment and since JSONP has no error handling and fails silently (per your IBM article reference and personal experienceSmile | :) , I'm having trouble tracking down what might be going wrong in my local environment. I confirmed that the $.jmsajaxurl function returns a value (URL/ServiceName.asmx/WebMethodName?var1="something"&var2="something"&var3="something"&var4="something"&var5="something") The "&" were placed during the copy-paste.
 
Any help/insight you can provide is greatly appreciated.
 
Regards,
Hasheen D
AnswerRe: Great article, but curiousmemberHomam Hosseini4 Nov '09 - 6:31 
No there's no special configuration in my ststem, I wrote and tested this code in VS.NET 2008 and IIS7 environment. But it should work also with IIS6 as well.
 
Just use a HTTP sniffer, Firebug, to see what data your're sending and receiving from the service.
Questionanother implementation: what do you think about it ?memberdadox19 Oct '09 - 20:44 
Very good article, thank you for sharing !
 
I found another method from IBM, have you read this:
http://www.ibm.com/developerworks/webservices/library/ws-wsajax/
 
I haven't try it yet, but they don't speak about cross-site problems...
I will try and post the results...
 
Bye
AnswerRe: another implementation: what do you think about it ?memberHomam Hosseini24 Oct '09 - 7:50 
the whole idea behind JSONP is to enable browsers to call remote web services. it's not rocket science, very simple idea, here i just collected all the required information somebody needs to use JSONP in ASP.NET.
GeneralRe: another implementation: what do you think about it ?memberdadox25 Oct '09 - 8:45 
Your solution works great !!!
Thank you very much for posting it.
I implemented it with a iPhone JavaScript app calling asp.net ws
and it is a very efficent solution...
GeneralGood articlemembergaurav_verma_mca13 Oct '09 - 17:45 
Good article

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 13 Oct 2009
Article Copyright 2009 by Homam Hosseini
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid