I have a Django ModelForm which is displayed in the template by using using crispy forms. After the user fills out the fields and presses a Submit button, an email is sent at the backend using Django's core send_email.
The problem is that the call to send_email is synchronous, so the user has to wait for the next page to load (success/failure page) but in this time the user might press the Submit button again and this generates multiple POSTs, making multiple emails.
I want to use Vue.js to make the button inactive once the user presses it but only if it passes Django's form validation. Is there a way to detect this?
Add to your button :disabled="!readyToSend" where readyToSend can be returned by your data function or a computed propoerty.
Before submitting the form set this variable to false, afater receiving data from your API, reset it to true.
In the following example I've choosen to make readyToSend a computed proporty where it will return true if the form is valid and if the process is not waiting for the API response.
The complete Code Pen example is here
html file :
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>example</title>
</head>
<body>
<div id="app">
<h2>{{ message }}</h2>
<form #submit.prevent>
<input type="text" v-model="dataToSend" placeholder="Something to send">
<button type="button" :disabled="!readyToSend" #click="send">Send</button>
</form>
</div>
</body>
</html>
javascript:
var vm = new Vue({
el: '#app',
data: function(){
return {
message: "please enter your message and click on send.",
dataToSend: "",
sentAndWaiting: false,
}
},
methods:{
send: async function(){
this.sentAndWaiting = true;
// Send Data Here
this.message = "sending....";
try{
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let jsonResponse = await response.json();
}
catch(e){
this.message = e.message;
}
// reponse received ... do Something with it
this.reponseReceived();
},
reponseReceived: function(){
this.sentAndWaiting = false;
this.message = "Ok. Got The response.";
}
},
computed:{
readyToSend: function(){
return this.dataToSend.length > 0 && !this.sentAndWaiting;
}
},
});
in my browser I had to test this by going to the developper tools and limit my internet connexion to the GPRS and disabling cache:
Screenshot DevTools
Related
I'm having trouble getting the Messenger Checkbox plugin to work: the Facebook script loads fine, it parses the page well (I can see this with the debug version of the SDK), but the checkbox remains in "hidden" status.
This is an HTML sample of my page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TestCheckboxMessenger</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<!-- Load Facebook SDK for JavaScript -->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: "[my-app-id]",
autoLogAppEvents: true,
xfbml: true,
version: "v10.0",
});
FB.Event.subscribe("messenger_checkbox", function (e) {
if (e.event == "rendered") {
console.log("Plugin was rendered");
} else if (e.event == "checkbox") {
var checkboxState = e.state;
console.log("Checkbox state: " + checkboxState);
} else if (e.event == "not_you") {
console.log("User clicked 'not you'");
} else if (e.event == "hidden") {
console.log("Plugin was hidden");
}
});
};
</script>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/fr_FR/sdk/debug.js"
></script>
<div
class="fb-messenger-checkbox"
origin="https://[my-domain-name]/"
page_id="[my-page-id]"
messenger_app_id="[my-app-id]"
user_ref="[some-random-id]"
size="medium"
skin="light"
center_align="true"
></div>
<app-root></app-root>
</body>
</html>
I have carefully read the facebook documentation and the solutions proposed on StackOverflow, but the checkbox does not appear. I have taken into account the following points:
My page is served on HTTPS with a domain name that is whitelisted in my page options
The user_ref is a randomly generated id that is new on every page refresh
My app is in what was called "development mode" so I have Standard access to pages_messaging and I have admin role on the app (and I am connected to my account)
My Messenger webhook is live and working
As strange as it may seem, the conversation plugin works fine.
What conversation plugin looks like
Is there a method to debug the checkbox status? To know why it is hidden? Because I have no error message in the Chrome console and all this is very frustrating :)
Ok so, acccording to this Facebook Update, the checkbox plugin and some other features including optin mechanics, media messages, etc. have been deactivated in Europe and some other countries because of GDPR.
Facebook planned to restore them by Q1 2021, but now they are moving the timeline towards Q2 2021.
I don't understand why they don't put a warning message on the docs about these features... :(
I am trying to follow the instructions on this site (https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen) with my DJANGO app to make a PWA "Install to home screen' button.
I have SSL installed on the site, and it seems to me that the service worker is installed properly, I got the "Service Worker Registered" message back. However when I click the button nothing happens, the + sign does not appear in the URL bar as it should.
I have no idea what is causing the error, as there is no clear sign of anything not working properly.
My index.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A2HS demo</title>
<link href="{% static 'css/index.css' %}" rel="stylesheet">
<script src="{% static 'js/index.js' %}" defer></script>
<link rel="manifest" href="{% static 'manifest.json' %}">
</head>
<body>
<button class="add-button">Add to home screen</button>
</body>
</html>
My manifest.json:
{
"short_name": "Test site",
"name": "Test site",
"theme_color": "#062440",
"background_color": "#F7F8F9",
"display": "fullscreen",
"icons": [
{
"src": "assets/logo.png",
"type": "image/png",
"sizes": "192x192"
}
],
"start_url": "/index.html"
}
My index.js
// Register service worker to control making site work offline
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/static/js/service-worker.js')
.then(() => { console.log('Service Worker Registered'); });
}
// Code to handle install prompt on desktop
let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
addBtn.style.display = 'block';
addBtn.addEventListener('click', () => {
// hide our user interface that shows our A2HS button
addBtn.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
});
And my service-worker.js:
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open('fox-store').then((cache) => cache.addAll([
'/index.html',
'/static/css/index.css',
'/static/js/index.js',
])),
);
});
self.addEventListener('fetch', (e) => {
console.log(e.request.url);
e.respondWith(
caches.match(e.request).then((response) => response || fetch(e.request)),
);
});
I am trying to create a simple static website that uses AWS Cognito to authenticate users. That means I'm not using any advanced libraries but basing my code on the AWS example here.
If I use the default 'token' flow then the example works for my domain. However, as recommended by Amazon themselves in several places e.g. here I want to used 'code grant' flow, and as state in the example above I just uncomment line 221:
auth.useCodeGrantFlow();
However this fails causing the onFailure function to be called although oddly I do see the URL bar containing code=xxxxx. It appears there are more steps I need to do but all examples I find demonstrate the less favourable 'token flow'.
This is my specific index.html based on the above example:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Cognito Auth JS SDK Sample</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="stylesheets/styleSheetStart.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="dist/amazon-cognito-auth.min.js"></script>
<!-- To enable the advanced security feature -->
<!-- <script src="https://amazon-cognito-assets.<region>.amazoncognito.com/amazon-cognito-advanced-security-data.min.js">
</script> -->
<!-- E.g. -->
<!-- <script src="https://amazon-cognito-assets.us-east-1.amazoncognito.com/amazon-cognito-advanced-security-data.min.js">
</script> -->
</head>
<body onload="onLoad()">
<ul>
<li><a href="https://aws.amazon.com/cognito/" target="_blank"
title="Go to AWS Cognito Console">Cognito Console</a></li>
<li><a href="http://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html"
target="_blank" title="See Cognito developer docs">Docs</a>
</li>
</ul>
<h1>
<a href="http://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html" target="_blank">
<img src="img/MobileServices_AmazonCognito.png" alt="Amazon Cognito" title="Amazon Cognito"
style="width:144px;height:144px;"></a><br>
Amazon Cognito Auth Demo
</h1>
<!--removed for brevity -->
<div><br></div>
<div>
<p id="statusNotAuth" title="Status">
Sign-In to Continue
</p>
<p id="statusAuth" title="Status">
You have Signed-In
</p>
</div>
<div class="tabsWell">
<div id="startButtons">
<div class="button">
<a class="nav-tabs" id="signInButton" href="javascript:void(0)" title="Sign in">Sign In</a>
</div>
</div>
<div class="tab-content">
<div class="tab-pane" id="userdetails">
<p class="text-icon" title="Minimize" id="tabIcon" onclick="toggleTab('usertab');">_</p>
<br>
<h2 id="usertabtitle">Tokens</h2>
<div class="user-form" id="usertab">
<pre id="idtoken"> ... </pre>
<pre id="acctoken"> ... </pre>
<pre id="reftoken"> ... </pre>
</div>
</div>
</div>
</div>
<script>
// Operations when the web page is loaded.
function onLoad() {
var i, items, tabs;
items = document.getElementsByClassName("tab-pane");
for (i = 0; i < items.length; i++) {
items[i].style.display = 'none';
}
document.getElementById("statusNotAuth").style.display = 'block';
document.getElementById("statusAuth").style.display = 'none';
// Initiatlize CognitoAuth object
var auth = initCognitoSDK();
document.getElementById("signInButton").addEventListener("click",
function() {
userButton(auth);
});
var curUrl = window.location.href;
auth.parseCognitoWebResponse(curUrl);
}
// Operation when tab is closed.
function closeTab(tabName) {
document.getElementById(tabName).style.display = 'none';
}
// Operation when tab is opened.
function openTab(tabName) {
document.getElementById(tabName).style.display = 'block';
}
// Operations about toggle tab.
function toggleTab(tabName) {
if (document.getElementById("usertab").style.display == 'none') {
document.getElementById("usertab").style.display = 'block';
document.getElementById("tabIcon").innerHTML = '_';
} else {
document.getElementById("usertab").style.display = 'none';
document.getElementById("tabIcon").innerHTML = '+';
}
}
// Operations when showing message.
function showMessage(msgTitle, msgText, msgDetail) {
var msgTab = document.getElementById('message');
document.getElementById('messageTitle').innerHTML = msgTitle;
document.getElementById('messageText').innerHTML = msgText;
document.getElementById('messageDetail').innerHTML = msgDetail;
msgTab.style.display = "block";
}
// Perform user operations.
function userButton(auth) {
var state = document.getElementById('signInButton').innerHTML;
if (state === "Sign Out") {
document.getElementById("signInButton").innerHTML = "Sign In";
auth.signOut();
showSignedOut();
} else {
auth.getSession();
}
}
// Operations when signed in.
function showSignedIn(session) {
document.getElementById("statusNotAuth").style.display = 'none';
document.getElementById("statusAuth").style.display = 'block';
document.getElementById("signInButton").innerHTML = "Sign Out";
/* Removed for brevity */
openTab("userdetails");
}
// Operations when signed out.
function showSignedOut() {
document.getElementById("statusNotAuth").style.display = 'block';
document.getElementById("statusAuth").style.display = 'none';
document.getElementById('idtoken').innerHTML = " ... ";
document.getElementById('acctoken').innerHTML = " ... ";
document.getElementById('reftoken').innerHTML = " ... ";
closeTab("userdetails");
}
// Initialize a cognito auth object.
function initCognitoSDK() {
var authData = {
ClientId : '<Removed>', // Your client id here
AppWebDomain : '<Removed>', // Exclude the "https://" part.
TokenScopesArray : [<removed>], // like ['openid','email','phone']...
RedirectUriSignIn : '<domain removed>/index.html',
RedirectUriSignOut : '<domain removed>/index.html'
};
var auth = new AmazonCognitoIdentity.CognitoAuth(authData);
// You can also set state parameter - do I need to set this?
auth.setState('ABCDXYZ');
auth.userhandler = {
onSuccess: function(result) {
alert("Sign in success");
showSignedIn(result);
},
onFailure: function(err) {
alert("Error!" + err);
}
};
// The default response_type is "token", uncomment the next line will make it be "code".
auth.useCodeGrantFlow();
return auth;
}
</script>
</body>
</html>
In dev tools I do see a call to https://<domain-name-removed>/oauth2/token but looks like it comes back with a 400 error.The response text is "error":"invalid_client".
Is there some additional configuration I need to do, or as suggested in the AWS docs for authorisation code grant flow I need to implement additional BE code? I feel the example code is lacking a full description for code grant flow.
According to
It turns out that when I created the the app client for the user pool I created it with a secret key. This key must be returned in the header as part of the authentication process which I wasn't doing; the aws example doesn't indicate how this is achieved. Instead direction is given to create the app client without an app secret key
If I understand your use case correctly you should not use an app client secret for this. The AWS example is indeed correct, the code you get in the url is meant to be used in another request in the process of acquiring the real code aka access_token.
I have the following example:
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.1.2/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.js"></script>
<script>mocha.setup('bdd');</script>
<script>
"use strict";
var assert = chai.assert;
var should = chai.should();
var vm = new Vue({
data: {
message: "Hello"
},
methods: {
loadMessage: function() {
this.$http.get("/get").then(
function(value) {
this.message = value.body.message;
});
},
}
});
describe('getMessage', function() {
let server;
beforeEach(function () {
server = sinon.fakeServer.create();
});
it("should get the message", function(done) {
server.respondWith([200, { 'Content-Type': 'application/json' },
JSON.stringify({message: "Test"})]);
vm.message.should.equal("Hello");
vm.loadMessage();
server.respond();
setTimeout(function() {
// This one works, but it's quirky and a possible error is not well represented in the HTML output.
vm.message.should.equal("Test");
done();
}, 100);
// This one doesn't work
//vm.message.should.equal("Test");
});
});
</script>
<script>
mocha.run();
</script>
</body>
</html>
I want to test that Vue asynchronously gets data from the server. Though, I mock out the actual HTTP request with Sinon FakeServer.
Naturally, directly after the call to loadMessage, the message is not yet set. I could use a timeout function for the test, but I believe there should be a better method. I've looked into respondImmediately, but it did not change. Also, there is the possibility to call a done() function. However, as I understand this, this done would need to be called within the loadMessage function, hence modifying the code under test.
What is the correct approach to handle this problem?
Edit: I have found at least a partial solution, but it seems to be still messy: call the done() function in the mocha unit test. When the assertion fails, it is at least shown in the HTML output. However, the assertion message is not as clear as in a normal test. Also, the technique still seems messy to me.
Since updating of vue component is done asynchronously you would need to use
// Inspect the generated HTML after a state update
it('updates the rendered message when vm.message updates', done => {
const vm = new Vue(MyComponent).$mount()
vm.message = 'foo'
// wait a "tick" after state change before asserting DOM updates
Vue.nextTick(() => {
expect(vm.$el.textContent).toBe('foo')
done()
})
})
Taken from official docs.
Uncaught ReferenceError: _onloadHook is not defined
Why? My code is below:
<!DOCTYPE html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<html>
<head>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script type="text/javascript">
//Initialize facebook
FB.init({
appId : '12345',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://www.abc.com/channel.html', // channel.html file
});
</script>
</head>
<body>
<div id="fb-root"></div>
<fb:send href="http://abc.com/blah" font="lucida grande" ref="codes_popup"></fb:send>
<fb:send href="http://abc.com/blah" font="lucida grande" ref="codes_popup"></fb:send>
</body>
</html>
Edit: When I have multiple this will happen. When I only have one "send" button , the error is not there.
For every extra "Send" button, the error occurs.
This is a bug in the Facebook Platform; it has already been reported as bug #20041.
Place the Facebook JS library and JS code scripts under the fb-root div:
<!DOCTYPE html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
//Initialize facebook
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://www.abc.com/channel.html', // channel.html file
});
</script>
<fb:send href="http://abc.com/blah" font="lucida grande" ref="codes_popup"></fb:send>
</body>
</html>
I have been getting the exact same error today.
As ifaour mentions, the FB documentation says that you need to place the FB <script> tags under the <div id="fb-root"></div>. However, in his example and in the FB documentation, they put the scripts directly under the <div id="fb-root"></div>. I was doing that and still getting the error the OP mentions. I was finally able to solve the problem by moving the FB <script> tags to the very bottom of the page, right before the closing </body> tag. I believe what was happening is that some of my other scripts were interfering with the loading of the FB scripts. Hope that helps.
You should call the facebook javascript using the upgraded async method. This will make sure that the whole DOM is loaded so that the fb:root is already on the page.
http://developers.facebook.com/docs/reference/javascript/FB.init/
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://www.yourdomain.com/channel.html', // Custom Channel URL
oauth : true //enables OAuth 2.0
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
Also critically important is to add support for OAuth 2.0 http://developers.facebook.com/blog/post/525/
oauth : true
As of Oct 1 if you don't have that your apps will stop working properly.