This is my jsonp code in which i am getting the data from online server and want to show in my 2 divs which is title and description. But the code is replacing my first div with the last content loaded by ajax_reponse.
function ajax_request() {
jsonp("http://example.com/jSonApi/json_data.php",
"ajax_response");
}
/**Response (Called when data has been retrieved)
*
* @param object data Javascript (JSON) data object received
* through <script> request
*/
function ajax_response(data) {
for(var key in data) {
document.getElementById("first").innerHTML=data[key];
}
}
function jsonp(url, callback)
{
if (url.indexOf("?") > -1) {
url += "&jsonp=";
}
else {
url += "?jsonp=";
}
url += callback + "&";
url += new Date().getTime().toString(); // prevent caching
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.getElementsByTagName('head')[0].appendChild(script);
}
This is my PHP code
<?php
// Connection to the database
include("connection.php");
$startQuery = mysql_query("select * from image_gallery where recid=474") or die (mysql_error());
if (mysql_num_rows($startQuery)>0){
$rs=mysql_fetch_array($startQuery);
$title = $rs["gallerytitle_en"];
$descp =trim(preg_replace('/\s\s+/', ' ', $rs["gallerydescp_en"]));
$jsonData=array("data_1" => $title , "data_2" => $descp);
}
mysql_free_result($startQuery);
echo $_REQUEST["jsonp"]."(".json_encode($jsonData).")";
?>