(function() {
main();
function main() {
jQuery(document).ready(function($) {
$.ajax({
type: 'post',
url: 'http://example.com/search.php',
data: { value: '123' },
cache: false,
success: function(returndata) {
$('#widget').html(returndata);
}
});
});
}
})();
<script src="http://example.com/widget.js" type="text/javascript"></script>
<div id="widget"></div>
When I paste widget on my site, it works perfectly and I get answers who is in div "widget" but if I paste this:
<script src="http://example.com/widget.js" type="text/javascript"></script>
<div id="widget"></div>
for another page it's not working. Can anyone help?
As of your comment, you are experiencing Cross domain restrictions (Same-origin policy). A workable solution for this is to serve your content from "search.php
" as jsonp
instead.
<?php
header('content-type: application/json; charset=utf-8');
$searchResults= array("Article 1", "Article 2", "Article 3");
echo $_GET['callback'] . '('.json_encode($searchResults).')';
?>
In your jQuery $.ajax
, you should set the dataType
to "jsonp
, and perhaps set the parameter crossDomain
to true
aswell.
(function() {
main();
function main() {
jQuery(document).ready(function($) {
$.ajax({
type: 'post',
dataType: 'jsonp',
crossDomain: true, // Shouldent be neccesary.
url: 'http://example.com/search.php',
data: { value: '123' },
cache: false,
success: function(returndata) {
$('#widget').html(returndata);
}
});
});
}
})();
Hope it works out for you.