im working on a flash game with django backend using swfobject to embed the swf into the view,
however when i do externalinterface.call() from flash in InternetExplorer(Chrome and Firefox are fine), it returns null
the flash game itself works perfectly
Django view and embed code:
<div id="game_container">
<div id='flashContent'></div>
</div>
<script type="text/javascript" src="swfobject.js"></script>
<script type='text/javascript'>
var flashvars={{flashvars|safe}};
var params={wmode:"opaque", allowscriptaccess:"always" };
var attributes={id:"flashContent", name:"flashContent"};
swfobject.embedSWF("{{SWF_URL}}", "flashContent", "{{ appsettings.SWF_WIDTH }}", "{{ appsettings.SWF_HEIGHT }}", "10.0.0", false, flashvars, params, attributes);
</script>
function fqlearn_isEventInteresting(data) {
ln_log(['isEventInteresting',data]);
if (!BASE_URL) BASE_URL = data.baseURL;
ln_log(['got lesson?',fqlearn_findLearningModule(data) != null]);
return fqlearn_findLearningModule(data) != null;
//shuld return either true or false.
}
Flash AS3 code:
var isInteresting:Object = false;
try {
isInteresting = ExternalInterface.call('fqlearn_isEventInteresting', data);
} catch (e:Error) {
trace("error calling external interface");
// Container does not support outgoing calls :/
rpc.forceLogUncaughtError("ExternalInterface.call problem",
e.name, e.toString(), e.getStackTrace());
rest.apply(restThis);
return;
} catch (e:SecurityError) {
// Security sandbox nonsense :/
throw e;
}
if (isInteresting == null) {
// Something went wrong :/
rpc.forceLogUncaughtError("ExternalInterface.call problem", "JS_returned_null_error");
}
if (isInteresting) {
trace("showing learning blackout")
dispatch(CoordinationEvent.newLEARNING_ABOUT_TO_SHOW());
learningPendingData = {
rest: rest,
restThis: restThis
};
ExternalInterface.call() from Flash in InternetExplorer(Chrome and Firefox are fine), it returns null . how do i fix this?
Fixed it: console.debug was choking up Internet Explorer. I removed those and it worked.
Related
I am trying to show/echo users location on a webpage using maxmind geoip2 paid plan, I also want to show different images based on the state/city names output.
For example, if my webpage shows the user is from New York, I would like to show a simple picture of New York, if the script detects the user is from Washington, the image should load for Washington.
This is the snippet I have tried but doesn't work.
<script type="text/javascript">
if
$('span#region=("New York")') {
// Display your image for New York
document.write("<img src='./images/NY.jpg'>");
}
else {
document.write("<img src='./images/different.jpg'>");
}
</script>
This is the code in the header.
<script src="https://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script>
var onSuccess = function(geoipResponse) {
var cityElement = document.getElementById('city');
if (cityElement) {
cityElement.textContent = geoipResponse.city.names.en || 'Unknown city';
}
var countryElement = document.getElementById('country');
if (countryElement) {
countryElement.textContent = geoipResponse.country.names.en || 'Unknown country';
}
var regionElement = document.getElementById('region');
if (regionElement) {
regionElement.textContent = geoipResponse.most_specific_subdivision.names.en || 'Unknown region';
}
};
var onError = function(error) {
window.console.log("something went wrong: " + error.error)
};
var onLoad = function() {
geoip2.city(onSuccess, onError);
};
// Run the lookup when the document is loaded and parsed. You could
// also use something like $(document).ready(onLoad) if you use jQuery.
document.addEventListener('DOMContentLoaded', onLoad);
</script>
And this simple span shows the state name in body text of the Html when the page loads.
<span id="region"></span>
now the only issue is the image doesn't change based on users location, what am i doing wrong here?
Your example is missing some code, but it looks like you are running some code immediately and some code in a callback, a better way to do it is to have all the code in the callback:
// whitelist of valid image names
var validImages = ["NJ", "NY"];
// get the main image you want to replace
var mainImage = document.getElementById('mainImage');
if (mainImage) {
// ensure there is a subdivision detected, or load the default
if(geoipResponse.subdivisions[0].iso_code && validImages.includes( && geoipResponse.subdivisions[0].iso_code)){
mainImage.src = "./images/" + geoipResponse.subdivisions[0].iso_code + ".jpg";
} else {
mainImage.src = "./images/different.jpg";
}
}
Then just have the image you want to replace be:
<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" id="mainImage" />
Notes:
If you are using a responsive image, make sure your transparent gif is the same ratio height of to width as your final image to avoid page reflows.
You will have to load the different.jpg in the onError callback as well.
Edit: Got it working now. The trick is to move the HTTP.get to the server-side and use the simple:reactive-method package to get result from a method.
I could use some help figuring out how to display the result of Meteor.HTTP.Get. The docs are sketchy and there's no topics here that relates to my case.
I'm searching Foursquare to find local farmers & markets around you. then display the result in a map (no map yet). Here's the code:
The start page:
<template name="locator">
<a class="button" href="{{pathFor route='locatorMap' query='group=farmers'}}">Farmers</a>
<a class="button" href="{{pathFor route='locatorMap' query='group=markets'}}">Markets</a>
</template>
The soon-to-be map page. Edited: Mar 31, 2015
<template name="locatorMap">
<div class="list">
{{#each venues}}
<p>{{name}}. {{location.lat}}, {{location.lng}}</p>
{{/each}}
</div>
</template>
The routing (lib/router.js)
Router.route('/locator', {name: 'locator'});
Router.route('/locator/map', {name: 'locatorMap'});
The helper (client/locator/locator.js). Edited: Mar 31, 2015
// A static list of venue categories
Foursquare.categoryId = { ... };
Template.locatorMap.helpers({
venues: function() {
var search_group = Router.current().params.query.group;
var search_categories = Foursquare.categoryId[search_group].join(',');
var search_location = Geolocation.latLng();
if (search_location) {
// using simple:reactive-method
return ReactiveMethod.call('FoursquareSearch', search_categories, search_location);
} else {
throw new Meteor.Error("No Location", "Failed to get ...");
}
}
});
The method (server/methods/foursquare.js). Edited: Mar 31, 2015
Meteor.methods({
FoursquareSearch: function(categories, location) {
check(categories, String);
check(location, Object);
try {
var search_result = HTTP.call(
'GET', 'https://api.foursquare.com/v2/venues/search?',
{
timeout: 5000,
params: { ... }
}
);
return search_result.data.response.venues;
} catch (_error) {
throw new Meteor.Error("No Result", "Failed to fetch ...");
}
}
});
I can see data on the console. But i'm just not sure how how to pass it into a template helper. If you guys need more info, just let me know.
Any help is appreciated. Thx!
The question is really just: "How do I call a method from a helper?", which is answered here and here. However, in order for those solutions to work, you'll need your method to return a value rather than making an asynchronous HTTP call (which returns undefined). The path of least resistance is to define your FoursquareSearch method only on the server (put it under the /server directory) and to use a synchronous method invocation. For example:
Meteor.methods({
FoursquareSearch: function(cat) {
check(cat, String);
var search_location = Geolocation.latLng();
if (search_location) {
try {
// fill in the blanks here with params, timeout, etc.
var result = HTTP.get(...);
return result.data.response;
} catch (_error) {
throw new Meteor.Error("No Result", "Failed to fetch...");
}
}
}
});
i am relatively new in django and angualarJs.The problem is that angularJs is not responding the get method properly.I have a webpage developed by django where i have a search field.For the execution of search i use a angularJs functionality that is ng-submit and write angularJs code to return value using get method.May be i made a mistake here.you can see my code... here is my template which containing the angularJs also...
<div class="navbar navbar-default " ng-controller="NavCtrl">
<form action="" class="navbar-form navbar-right" ng-submit="search()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="term"></input>
</form>
</div>
<script>
app.controller("NavCtrl", ['$scope', '$http', '$location', '$q', '$timeout',
function NavCtrl($scope, $http, $location, $q, $timeout) {
$scope.results = ["Test"];
$scope.term = "";
$scope.reqs = "5";
$scope.pics = "45";
$scope.ddata = "asdasd";
$scope.ddata = $http.post("{% url 'get-nav-info' %}").success(
function (result) {
//$scope.reqs = result.data.data.num_request;
//$scope.pics = result.data.data.num_photo;
return result.data;
}
);
//$scope.reqs = $scope.ddata.num_request;
//$scope.pics = $scope.ddata.num_photo;
$scope.search = function () {
//alert("test");
//$location.absUrl("{% url 'search-term-show' %}").search({'term':$scope.term}).apply();
//$location.path("{% url 'search-term-show' %}").search({'term':$scope.term}).apply();
$http.get("{% url 'search-term-show' %}?term=" + $scope.term).success(function (result) {
return result.data;
});
//$scope.$apply();
}
}
]);
</script>
now the problem is that while i press enter ,there is no result,but if i manually write this URL which is http://www.kothay.com/searchphoto/?term=a in the address bar then the result is showing .In mention,this url is the that url which should be appear in the address bar when i press the enter to search my photos.But with the enter press its not appearing in the address bar and that's why the results are not showing.I hope you can understand what i am trying to say.May be there is a mistake in my code.Please help me to fix this problem.
You are doing thing wrong.
1st, the success is a defer of get, so return result.data and returns it to the get deferred and there it goes to the heaven. So if you would like to keep the current architecture it should look more like this
$scope.search = [];
getsearch = function () {
$http.get("{% url 'search-term-show' %}?term=" + $scope.term).success(function (result) {
$scope.search = result.data;
});
};
getsearch();
2nd that can still not update your UI cuz if the ctrl function is over and the digest is over before your response it wont update your UI cuz its in another scope (not $scope, but the programmatically term scope). The solution to this is to put your data in a service and in your ctr just do.
function ctrl($scope, myservice){
$scope.data = myservice;
}
ng-repeat="x in data.results"
Here is a full tutorial http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html
And last thing its just a good practice to always have .error(...)
I have an upload form with plupload and a checkbox with boolean value after the plupload div.
I want to change the value of the url in plupload if the checkbox is checked.
Here is my code
<div id="uploader">
<p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
</div>
<input id="compressFiles" type="checkbox" name="compressFiles" style="margin:10px 0 0 10px;" value="compress" checked="checked" />
$(function() {
$("#compressFiles").change(function(){
if( $("#compressFiles").is(':checked') ){
compress = 'compress';
}
else{
compress = 'no';
}
})
$("#uploader").plupload({
runtimes : 'gears,flash,html5,html4,browserplus,silverlight',
url: 'uploadHandler.php?compressFiles=' + compress,
max_file_size : '1000mb',
max_file_count: 20, // user can add no more then 20 files at a time
unique_names : true,
dragdrop : true,
multiple_queues : true,
// Addeb by LG - problem with FF
filters: [
{title: "All", extensions: "*"}
],
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Flash settings
flash_swf_url : 'js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url : 'js/plupload.silverlight.xap',
init : {
FilesAdded: function(up) {
if( $("#compressFiles").is(':checked') ){
compress = "no"
}
else{
compress = "no"
}
}
}
});
// Client side form validation
$('form').submit(function(e) {
var uploader = $('#uploader').plupload('getUploader');
// Validate number of uploaded files
if (uploader.total.uploaded == 0) {
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('UploadProgress', function() {
if (uploader.total.uploaded == uploader.files.length){ alert("coucou");
$('form').submit();}
});
uploader.start();
} else
alert('You must at least upload one file.');
e.preventDefault();
}
});
});
The value of url variable is defined first time page load with compress value. I tried 1000 thinhs but impossible to refresh the compress value in the url when checkbox change.
I hope my problem is clear, dont speak english very good.
Thanks for help
Simply bind to the "BeforeUpload" event and you can change the uploader.settings to fit your needs.
this.uploader.bind('BeforeUpload', function(uploader, file) {
if($("#compressFiles").is(':checked')) {
uploader.settings.url = "uploadHandler.php?compressFiles=compress";
} else {
uploader.settings.url = "uploadHandler.php?compressFiles=no";
}
});
In plupolad v3 chaging settings.url won't work. You have to use
uploader.setOption('url', 'your/url/here');
How could I make this work? I want to load a php file like this:
Click button.
Call Javascript function.
In Javascript function create an img with src file.php.
This should force the loading of the php. Here is the code.
<script type="text/javascript">
var d;
function callSave() {
alert ('calling');
if (d) document.body.removeChild(d);
// d = document.createElement("script");
d = document.createElement("img");
d.src = "savepages.php";
//d.type = "text/javascript";
document.body.appendChild(d);
}
</script>
Then in savepages.php I do another alert to verify that the php is called and it isn't. Here is the savepages.php.
<?php
echo "alert('from the php');";
?>
The alert from the php doesn't happen. Is there a different element type that will force loading of the php? I don't have ajax installed, so I need a workaround like this.
Thanks.
You could use an iframe element
<script type="text/javascript">
var d;
function callSave() {
alert ('calling');
if (d) document.body.removeChild(d);
d = document.createElement("iframe");
d.src = "savepages.php";
document.body.appendChild(d);
}
</script>
Found out the better way to handle this. There is this simple code that explains how to call a javascript function from a form event and from that javascript function load a PHP file. The code found at http://daniel.lorch.cc/docs/ajax_simple/ is also given here:
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function validate(user) {
http.abort();
http.open("GET", "validate.php?name=" + user, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('msg').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
<h1>Please choose your username:</h1>
<form>
<input type="text" onkeyup="validate(this.value)" />
<div id="msg"></div>
</form>
validate.php
<?php
function validate($name) {
if($name == '') {
return '';
}
if(strlen($name) < 3) {
return "<span id=\"warn\">Username too short</span>\n";
}
switch($name) {
case 'bob':
case 'jim':
case 'joe':
case 'carol':
return "<span id=\"warn\">Username already taken</span>\n";
}
return "<span id=\"notice\">Username ok!</span>\n";
}
echo validate(trim($_REQUEST['name']));
?>