JSONP for cross domain communication solution using with javascript and PHP

JSONP for cross domain communication solution using with javascript and PHP

Last year in Feb I heard about JSONP and really liked the JSONP solutions. JSONP allows you to make an HTTP request outside your own domain
JSONP consume the Web Services from JavaScript code. Earlier I worked on so on AJAX but there is issue with working or communication issue with cross domain sites.

JSONP for cross domain communication solution using with javascript and PHP
JSONP for cross domain communication solution using with javascript and PHP

XMLHttpRequest is blocked from making external requests.

JSONP for cross domain communication solution using with javascript and PHP

JavaScript code to make a JSONP call will as follows:

[viral-lock message=”Solution code is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]

function common_jsonpRequest(url, name, query) {

 if (url.indexOf("?") > -1)
 url += "&jsonp="
 else
 url += name + "&";
 if (query)
 url += encodeURIComponent(query) + "&";
 url += new Date().getTime().toString(); // prevent caching

 var JSONPscript = document.createElement("script");
 JSONPscript.id = 'wordpressapi_jsonpRequest';
 JSONPscript.setAttribute("src", url + "&CacheBuster=" + Math.random());
 JSONPscript.setAttribute("type","text/javascript");

 // write the jsonp script tag
 document.body.appendChild(JSONPscript);
 //script.text = "";

}

function returncall (data){
 alert(data);
// you can use data as a variable also.
}

[/viral-lock]

In same javascript you should write the returning function as above.

You can call JSONP this function as follows;

<a href="http://images.purabtech.in/JSONP-request.gif">
<img class="alignnone size-medium wp-image-1167" title="JSONP-request" src="http://images.purabtech.in/JSONP-request-300x125.gif" alt="" width="300" height="125" />
</a>
common_jsonpRequest(base_url+'getData.php?jsonp=mycallback&name=for_wordpressapi');

Notel: getData.php file will beahave like externaal javascript file so handle this file carefully.
getData.php sample file.

<?php
$data = "this is our dynamic data";
if($_REQUEST['name']=='for_wordpressapi'){

echo "returncall(".$data.")";

}

?>&nbsp;

This will return the “this is our dynamic data” as a alert.

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

2 thoughts on “JSONP for cross domain communication solution using with javascript and PHP”

  1. Exceptional webpage. My class mates and I were just discussing this the other night. Also your webpage looks great on my old laptop. Now thats uncommon. Nice work.

Leave a Reply

Your email address will not be published.