Sunday, December 19, 2010

Cross Domain Posting using PHP and JavaScript: ITS POSSIBLE!

12/19/2010

Well.....finally i have worked out how to post cross-domain data which is restricted by browser's security policies.
WHAT IS IT??
This will be used for posting AJAX requests via java-script to any web-service or web-page in any DOMAIN and also get back the results from there.
Source: http://amiteighty82.blogspot.com/

HOW TO USE IT ?

Simply use this function in your java script
function jsonp(url, callback, name, query) 
{
    if (url.indexOf("?") > -1)
        url += "&jsonp="
    else
        url += "?jsonp="
    url += name + "&";
    if (query)      
        url += query+ "&";
    url += new Date().getTime().toString(); // prevent caching
    var script = document.createElement("script");
    script.setAttribute("src", url);
    script.setAttribute("type", "text/javascript");
    document.body.appendChild(script);
}

CALLING THIS FUNCTION from JavaScript :

jsonp("url of web page to be posted","", "function to be called back to receive result from the page","parameters  to be passed");
eg:
jsonp('http://example.com/test.php', '', 'loadData', "userid=" + userid + "&name=test" );

ON WEB SERVICE :(like on http://example.com/test.php):
<?php
if(isset($_REQUEST['jsonp']) && $_REQUEST['jsonp'] !== '')
{
 loadData("Welcome to cross domain posting.)";
}
>?
//callback here is your function (loadData) that should be present on your JavaScript

BACK ON JAVASCRIPT:
loadData(result)
{
 alert(result);
}
Which will alert you 'Welcome to cross domain posting.' that i have passed from test.php page in another domain.
This is it...
If u have any query plz let me know .......best O" lcuk...:)

Written by

Arvind is a web developer, programmer and blogger. He has expertise in PHP, Magento, WordPress, jQuery, JavaScript, HTML5 and CSS3. He loves to develop good looking websites with strong backend.

3 comments :

  1. Man, you forgot deleting the script node afterwards. What if I do, say, 50000 crossdomain requests (think web application here, like Twitter client), I'll get 50000 nodes in DOM.

    ReplyDelete
  2. Cool post. That's exactly what I was looking for.

    dimi :)

    ReplyDelete
  3. Does this works in all browsers

    ReplyDelete

We would love to hear from you...

 

© 2014 Web Speaks . All rights resevered. Designed by Templateism