Alternative to JSONP for One-shot webservices #AJAX
Cross-domain restrictions prevent you from exchanging data from domainA.com to domainB.com , however, there are some workarounds, such as JSONP, where you trick the browser into loading a script from another domain, and have that script call back to your page – It does mean however, that the webservice has to be specifically designed to include the call back to your javascript callback function.
However, this is another workaround that does not require any specific format in the return value of the webservice, in effect, the return value is ignored, so it’s only for one-shot “fire and forget” webservices.
Here’s an example, where you can send email from javascript, using the webservice from www.directtomx.com
Email = {
Send : function (to,from,subject,body,apikey)
{
if (apikey == undefined)
{
apikey = Email.apikey;
}
var nocache= Math.floor((Math.random() * 1000000) + 1);
var strUrl = “http://directtomx.azurewebsites.net/mx.asmx/Send?”;
strUrl += “apikey=” + apikey;
strUrl += “&from=” + from;
strUrl += “&to=” + to;
strUrl += “&subject=” + encodeURIComponent(subject);
strUrl += “&body=” + encodeURIComponent(body);
strUrl += “&cachebuster=” + nocache;
Email.addScript(strUrl);
},
apikey : “”,
addScript : function(src){
var s = document.createElement( ‘link’ );
s.setAttribute( ‘rel’, ‘stylesheet’ );
s.setAttribute( ‘type’, ‘text/xml’ );
s.setAttribute( ‘href’, src);
document.body.appendChild( s );
}
};
Then it would be called like this –
window.onload = function(){
Email.apikey = “– Your api key from directtomx.com —“;
Email.Send(“swordfish1234@printfromipad.com”,”info@webtropy.com”,”Sent from JS API”,”Worked!”);
}
It works by pretending that the webservice call is actually a CSS stylesheet. The CSS will be invalid, but this type of error would be swallowed silently by the browser.