I have a bookmarklet that when clicked opens up a div popup on their current page(e.g. http://www.cnn.com). This div has a button that that when clicked makes a jQuery.get request to my application domain. This is all working fine, but I am getting an error on the response. This is the function that makes the request
function postWishXML(){
jQuery(".ServerResponse").ajaxError(function(event, XMLHttpRequest, ajaxOptions){
//entering here
});
var Wish = wishObject();
if(Wish == false)
{
jQuery('.ServerResponse').html('Please enter a gift title');
jQuery('.GiftText').val('');
}else
{
jQuery('.ServerResponse').html('');
var WishXML = createXMLTags(Wish);
jQuery.get(Root+'/apps/shop/toolbar/WishlistPopup.ashx',
{'sap':Cookie,'wish':WishXML},
Response,
'text'
);
}
}
this is the server code
public void ProcessRequest (HttpContext context) {
if (SecurityContext.IsAuthenticated || SecurityContext.IsSemiAuthenticated)
{
if (!string.IsNullOrEmpty(context.Request["wish"]))
{
string res = "Your wish has been added";
context.Response.ContentType = "text/plain";
context.Response.Write(res);
context.Response.End();
}
}
Is my problem something to do with cross domain scripting or syntax?
Thanks
I think you’re right. It looks like you’re hitting on a cross-site scripting limitation.
Remember, you’re inserting your javascript code into the target website’s code. Therefore, it’s just like the code is running from their page. In other words, you’re attempting to make an AJAX request from within the page (e.g., http://www.cnn.com) and retrieve data from your site (another domain).
One solution I found in an article here. This is the gist:
Make your server script return javascript that will be eval’ed.
A second, probably more preferred option is to use JSONP. Essentially, your server will respond with JSON data wrapped in a named function. You tell the jQuery.ajax request you expect a jsonp response and what the name of the returned function will be. This is pretty much doing the above, but with a little more safety and syntactic sugar wrapped around it.
This would be the PHP version, but it should get the point across. Assume all the data you need is in $data and keep in mind that you could put anonymous functions in the JSON structure to be eval’ed in success handler.
The javascript:
To give proper credit, I stole and modified this JSONP example from Andrew Moore’s answer for this question