Recaptcha.create works locally but not on server - javascript

I've got an Google Recaptcha it uses the Recaptcha.create. However for some reason the Recaptcha.create works locally but not on the server. Here is my html and js.
HTML
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha"></div>
<div id="fError">Waiting for input.</div>
<script src="/assets/js/upload-flash.js"></script>
And this is the upload-flash.js
var captchaused = false;
function showRecaptcha() {
Recaptcha.create("6LfHYvgSAAAAAJ9G7fNYW5vwQkxUZDNSFhweiOPp", "recaptcha", {
theme: "clean",
callback: Recaptcha.focus_response_field});
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
if(captchaused === false){
captchaused = true;
showRecaptcha();
} else {
Recaptcha.reload();
}
}
}
/*... and after this comes the uploading part. Removed it so that it doesn't become too long*/
Here are pictures
Local
Server

I made a mistake with the public and private keys I get from google and used the wrong ones. After changing the keys I used it started working perfectly again.

Related

correct javasript code execution in flask

I tried to use click on button:
#app.route("/")
def test_edition_open():
return render_template("index.html")
my index.html file is:
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
The main part is just two buttons:
<div class = "counter">
<button class = "minus">-</button>
<div class = "result">1</div>
<button class = "plus">+</button>
</div>
I tried to make My script.js file work in flask. The code is very simple, it should add numbers by clicking on button:
const plus = document.querySelectorAll('.plus');
const minus = document.querySelectorAll('.minus');
const result = document.querySelectorAll('.result');
function min()
{
return function (ev)
{
if (ev.target.nextElementSibling.innerHTML > 0)
{
return --ev.target.nextElementSibling.innerHTML;
}
}
}
function pl()
{
return function (ev)
{
return ++ev.target.previousElementSibling.innerHTML;
}
}
minus.forEach(function (dominus)
{
dominus.addEventListener('click', min());
})
plus.forEach(function (doplus)
{
doplus.addEventListener('click', pl());
})
In https://playcode.io this code worked well. How should I solve this problem?
Make sure that script file successfully connected to html file. to check this add console.log("File Connected") in your script.js file. Then open your browser console to check that console message is logged correctly. If not then try to linked your static file correctly. How to set static_url_path in Flask application
Or you can put your Javascript code in html file using script tag.
Something like this:
<script> your javascript code here</script>

How to put two function calls in a HTML file?

I'm learning Solidity (for smart contracts) and now need to design a UI to interact with a deploy contract.
Note: If the question is not relevant to this forum, please kindly let me know (instead of downvoting) and I'll remove it.
My HTML and .js files are as below. The problem is that, when I include both "distribute()" and "update_exchange_rate()" functions in .js file, my HTML file would not work. But I wouldn't have any problem if I remove either of them from .js file.
Question: Why am I having this problem? How to solve the above problem? Can I have multiple functions (definitions) in window.app?
Edit: If I put both functions in .js files, I also get webpack error. But the error will disappear if I remove one of the functions.
<!DOCTYPE html>
<html>
<head>
<script src="./app.js"></script>
</head>
<body>
<h1>MetaCoin</h1>
<h2>Example Truffle Dapp</h2>
<br>
<br><label for="amountB">Exchange rate:</label><input type="text"
id="amountA" placeholder="e.g., 95"></input>
<br><label for="receiverA">ReceiverA:</label><input type="text"
id="receiverA" placeholder="e.g., 95"></input>
<br><label for="receiverB">ReceiverB:</label><input type="text"
id="receiverB" placeholder="e.g., 95"></input>
<br><br><button id="send1" onclick="App.distribute()">Send
MetaCoin</button>
<br><br>
<br><label for="amountB">Exchange rate:</label><input type="text"
id="amountB" placeholder="e.g., 95"></input>
<br><br><button id="send2"
onclick="App.update_exchange_Rate()">update_exchange_Rate</button>
<br><br>
<br>
</body>
</html>
and my js file is:
import "../stylesheets/app.css";
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import metacoin_artifacts from '../../build/contracts/MetaCo.json'
var MetaCo = contract(metacoin_artifacts);
var accounts;
var account;
window.App = {
start: function() {
MetaCo.setProvider(web3.currentProvider);
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is
configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
});
},
setStatus: function(message) {
var status = document.getElementById("status");
status.innerHTML = message;
},
distribute: function() { // XXX Here is where the problem occures!
var amountA = parseInt(document.getElementById("amountA").value);
var receiver1= document.getElementById("receiverA").value;
var receiver2 = document.getElementById("receiverB").value;
var meta;
MetaCo.deployed().then(function(instance2) {
meta = instance2;
return meta.distribute(receiver1,receiver2, amountA,{from: account});
})
}
update_exchange_Rate: function() { // XXX Here is where the problem occures!
var amountB = parseInt(document.getElementById("amountB").value);
var meta1;
MetaCo.deployed().then(function(instance3) {
meta1 = instance3;
return meta1.update_exchange_Rate(amountB,{from: account});
})
}
};
window.addEventListener('load', function() {
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source. If you find
that your accounts don't appear or you have 0 MetaCoin, ensure you've
configured that source properly. If using MetaMask, see the following
link.
Feel free to delete this warning. :)
http://truffleframework.com/tutorials/truffle-and-metamask")
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
} else {
console.warn("No web3 detected. Falling back to http://localhost:8545.
You should remove this fallback when you deploy live, as it's
inherently
insecure. Consider switching to Metamask for development. More info
here:
http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node +
in-dapp id mgmt / fail)
window.web3 = new Web3(new
Web3.providers.HttpProvider("http://localhost:8545"));
}
App.start();
});
Let's take only this button, the other has the exact same problem...
<button id="send2" onclick="App.update_exchange_Rate()">update_exchange_Rate</button>
The onclick attribute expects to receive a Function. That function is then called on every click. But the function does not return a function itself...
App.update_exchange_Rate() will get executed as soon as that part is seen by the browser, and it's return value used. But that's not what we want! We want that function to be executed... So we'd need to give the function, and not the call to the attribute, like so:
<button id="send2" onclick="App.update_exchange_Rate">update_exchange_Rate</button>
or
<button id="send2" onclick="function(){App.update_exchange_Rate();}">update_exchange_Rate</button>
Now, if you do that you'll certainly end up in a scope you are not expecting. You aren't using this in the function so I'll skip that scoping part, you can read about it later if need be.

How to call external javascript function to ClientSideEvents.Click event?

I have DevExpress().Button on a website which should take specific grid value from a focused row and pass it to external function.
Here is my button:
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnMyName";
settings.Width = 120;
settings.Height = 25;
settings.Text = "MyText";
settings.Styles.Native = true;
settings.ClientEnabled = true;
settings.ClientSideEvents.Click = "function(s, e) { gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'MyValue', OnGetRowValues); }";
}).GetHtml()
I simply can't reach OnGetRowValues function - always get the same exception:
Uncaught ReferenceError: OnGetRowValues is not defined
I have the script in the same folder as my .cshtml file and tried to reference it with <script src=""></script> in relative and absolute way. I tried to put the code to function directly between script tags to the cshtml page but nothing works and I get always the same error. The only solution which so far worked was to put the entire script as assingment to ClientSideEvents.Click but because the OnGetRowValues function is big, it will become messy and downright unpractical solution. Any help will be appreciated.
Go through Client-Side Events documentation and implement using below example:
<script type="text/javascript" src="~/Content/js/index.js"></script>
<script type="text/javascript">
function ButtonClick(s,e)
{
gridView.GetRowValues(gridView.GetFocusedRowIndex(), 'ShipName', OnGetRowValues);
}
</script>
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnGetSelectedRowValue";
settings.UseSubmitBehavior = true;
settings.ClientSideEvents.Click = "ButtonClick";
}).GetHtml()
#Html.Action("GridViewPartial")
index.js
// Value contains the "EmployeeID" field value returned from the server, not the list of values
function OnGetRowValues(Value) {
// Right code
alert(Value);
// This code will cause an error
// alert(Value[0]);
}
Hope this help..

JS oop not work in Internet Explorer

I'm developping a web site using WAMP, this is a part of code in my website. I even checked this block of code mentioned below.
html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="Functions/jquery.min.js"></script>
<script type="text/javascript" src="Functions/listControl.js"></script>
<script type="text/javascript">
var users= new regUsers('load','bef','full');
</script>
</head>
<body>
</body>
</html>
javascript page
function regUsers(id,pos,detail)
{
/*
usr001 all users
usr002 search users on keyword
*/
var self=this
this.count=0;
this.id='#' + id;
this.pos=pos;
this.amount=0;
this.detail=detail;
this.countReset= function(){this.count = 0;};
this.getList=function()
{
console.log('count : ' + self.count);
$.ajax({
type:'POST',
url:'Functions/list.php',
data:{req:'usr001',off:this.count,detail:this.detail,amount:self.amount},
success:function(ans){
if(ans=="")
return;
else
{
self.count += parseInt(self.amount);
switch(self.pos)
{
case 'bef':
$(ans).insertBefore(self.id);
break;
case 'app':
$(self.id).append(ans);
console.log(ans);
break;
}
}
}
});
}
this.findRec=function(keyW='',cls,field)
{
if(keyW=='')
{
self.getList();
return;
}
$.ajax({
type:'POST',
url:'Functions/list.php',
data:{req:'usr002',keyW:keyW,detail:this.detail,field:field},
success:function(ans){
self.countReset();
$("."+ cls).remove();
switch(self.pos)
{
case 'bef':
$(ans).insertBefore(self.id);
break;
}
}
});
}
}
This code is properly work in Firefox, but not in internet explorer. In Internet explorer console, it is said that regUsers is not difined.
It could be that Internet Explore loads the JS files after it loads the inline script, I know it may not make much sense to do that but it might be a particular IE issue. What you could do is put your var users= new regUsers('load','bef','full'); in a third JS file or you can assign the value to users in unload of the body tag i.e.
<body onload="users = new regUsers('load', 'bet', 'full')">
. . .
</body>
This will insure that the your initialization code is executed after the webpage has loaded. Since users is declared with var it becomes a global variable, declaring with var users = … would have made it visible only in the scope of onload.

Play Framework 2.1 websockets in Chrome

I can't seem to get websocket communication to work in the Play Framework version 2.1.
I created a simple test that does nothing but send messages back and forth with a push of a button. All the code for it is below. But nothing shows up except for the button.
Has anybody seen this problem or can someone tell me what I may be doing wrong in the code below?
I am using the latest version of Chrome.
Here is my simple setup.
In Application.java
public static Result index() {
return ok(index.render());
}
public static WebSocket<String> sockHandler() {
return new WebSocket<String>() {
// called when the websocket is established
public void onReady(WebSocket.In<String> in,
WebSocket.Out<String> out) {
// register a callback for processing instream events
in.onMessage(new Callback<String>() {
public void invoke(String event) {
System.out.println(event);
}
});
// write out a greeting
out.write("I'm contacting you regarding your recent websocket.");
}
};
}
In Routes File
GET / controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
GET /greeter controllers.Application.sockHandler()
In Index.Scala.html
#main(null) {
<div class="greeting"></div>
<button class="send">Send</button>
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var sock = new WS("#routes.Application.sockHandler()")
sock.onmessage = function(event) {
$('.greeting').append(event.data)
}
$('button.send').click(function() {
sock.send("I'm sending a message now.")
});
})
</script>
}
In Main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
The problem is in
var sock = new WS("#routes.Application.sockHandler()")
you have to specify the protocol and the complete url in the format: ws://localhost:9000/greeter.
Check this question to do it in javascript: How to construct a WebSocket URI relative to the page URI?
you can use a Route's webSocketURL() method to retrieve a url that can be passed to a WebSocket's constructor. Here's an example from Play's websocket-chat sample code:
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("#routes.Application.chat(username).webSocketURL()")
var sendMessage = function() {
chatSocket.send(JSON.stringify(
{text: $("#talk").val()}
))
$("#talk").val('')
}
// ...
So in your code you can use something like
var sock = new WS("#routes.Application.sockHandler().webSocketURL()");
Personally I don't like intermingling interpolated code with JS, since I think that any code executing on the client should only be concerned with the state of the client, and not the server (not to mention it makes refactoring the script out into an external file impossible), so I tend to do something like this:
<div class="container app-container"
data-ws-uri="#routes.Application.WSUri.webSocketURL()">
.......
</div>
Then in my JS I can just do something like
var sock = new WS(document.querySelector(".app-container").dataset.wsUri);
// ....

Categories