This week, I have been mostly getting JSONP
I've just finished writing a test harness for a sms texting service. While writing this little tool I ran into a problem with cross site scripting issues.
Essentially its a form that is submitted to a page which then invokes methods to deal with the faked sms. It actually plays the part of the sms gateway host and saves me 50pence a shot!
The form submission is via AJAX, but because its on a different domain I get no success or useful error responses. This is where JSONP comes in.
As of jQuery 1.2 you can get JSON data from another domain if you add a JSONP callback and a little bit of handling on the server.
You also get the proper success and error responses.
The form looks a little like this:
<form action="http://someOtherDomain/cross-site.php" method="get">input1:<input id="input1" name="input1" value="suits you sir"/></form><button type="button" id="btnsubmitjson">jsonp submit</button><div id="response"></div>
The javascript that handles the button click event appends the JSON callback to the url and then submits the form with the power of jQuery:
function submitjson(){posturl = $("form").attr('action');posturl += "?jsoncallback=?"; //append the JSON call back$.getJSON(posturl, $("form").serialize(), function(data) {$('#response').text(data.name);});
}
And the final part (which is not so obvious) is the response required, generated by the server:
<?php$data = '{"name" : "'.$_GET['input1'].'"}';echo $_GET['jsoncallback'].'('.$data.');';?>
And its this last magic bit in the responding with $_GET['jsoncallback'] which makes it all work!
Now I can point my tool where ever I like, AND get the right responses (ah yeah).
Labels: AJAX, Cross site, jQuery, JSONP
0 Comments:
Post a Comment
<< Home