Home > Uncategorized > Alternative to JSONP for One-shot webservices #AJAX

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.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: