Dart: AJAX form submit - ajax

Please note: I am not interested in using Polymer for this; I want to use "pure" Dart!
I am trying to build a simple sign-in screen for my Dart app, and am having difficulty getting the two form variables (email and password) to POST to the server-side:
Here's my main HTML file (myapp.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sign in</title>
<link rel="stylesheet" href="assets/myapp/myapp/myapp.css">
<link rel="stylesheet" href="assets/myapp/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="signinForm" method="POST" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" name="email" placeholder="Email address">
<input type="password" class="input-block-level" name="password" placeholder="Password">
<button class="btn btn-large btn-primary" id="signinBtn" type="submit">Sign in</button>
</form>
</div>
<script type="application/dart" src="myapp.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
Here's my main Dart file (myapp.dart):
import 'dart:html';
void main() {
querySelector("#signinForm")
..onClick.listen(handle);
}
void handle(MouseEvent mouseEvent) {
mouseEvent.preventDefault();
FormElement formElement = mouseEvent.target as FormElement;
var url = "http://localhost:8080/myapp/signinService";
var request = HttpRequest.request(
url,
method: formElement.method,
sendData: new FormData(formElement)
).then(onDataLoaded);
}
void onDataLoaded(HttpRequest req) {
String response = req.responseText;
if(response == 1)
window.alert("You are signed in!");
else
window.alert("Sign in failed. Check credentials.");
}
When I run this in a browser I see the sign in screen appear, but when I click the signin button nothing happens, and Firebug throws a bunch of errors on the cross-compiled, obfuscated, minified JavaScript:
: CastError: Casting value of type qE to incompatible type Yu
I want this to be an AJAX request so that the user does not have to experience a page reload (the intent here is to be a single page app).
Any ideas as to what's going on here? I'm almost 100% confident the issue isn't on the server-side, so for now I'm omitting to post server code. But I'll update my question with server code if need be.

here is an example how to do this
Forms, HTTP servers, and Polymer with Dart
When you change
void main() {
querySelector("#signinBtn")
..onClick.listen(handle);
}
to
void main() {
querySelector("form")
.onSubmit.listen(handle);
}
you have access to target
void handle(Event event) {
event.preventDefault();
FormElement form = event.target as FormElement;
...
}

Related

Unable to Programmatically invoke the invisible recaptcha challenge by ID

We have a set up with multiple forms on a single page. We are rendering each recaptcha successfully, however I'm struggling to invoke the recaptcha challenge programatically targeted to an ID.
Looking at the docs (https://developers.google.com/recaptcha/docs/invisible#programmatic_execute) my understanding is that I can pass an ID with the execute command so the response is filled into g-response within the correct form, otherwise the response defaults to the first g-response it finds on the page (which is no good for anything other than the first form on the page).
I've tried it with a slightly modified version of Googles own example, however we get the error message 'Invalid site key or not loaded in api.js: recaptcha123' even though the key is correct.
Does anyone have any idea how we might get this working?
<html>
<head>
<script>
function onSubmit(token) {
alert('thanks ' + document.getElementById('field').value);
}
function validate(event) {
event.preventDefault();
if (!document.getElementById('field').value) {
alert("You must add text to the required field");
} else {
grecaptcha.execute('recaptcha123');
}
}
function onload() {
var element = document.getElementById('submit');
element.onclick = validate;
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form>
Name: (required) <input id="field" name="field">
<div id="recaptcha123" class="g-recaptcha"
data-sitekey="XXXXXXXXXXXXXXXX"
data-callback="onSubmit"
data-size="invisible"></div>
<button id="submit">submit</button>
</form>
<script>onload();</script>
</body>
</html>
The following code works:
<html>
<head>
<title>reCAPTCHA demo: Explicit render after an onload callback</title>
<script>
var onSubmit = function(token) {
console.log('success!');
};
var onloadCallback = function() {
widgetId1 = grecaptcha.render('recaptcha', {
'sitekey' : 'XXXXXXXXXXXXXXXXXX',
'callback' : onSubmit
});
};
</script>
</head>
<body>
<script src="/wp-content/themes/kc_water_care_services/js/pristine.min.js"></script>
<form action="?" method="POST" id="contactForm">
<div class="form-group">
<label for="name">Name (required)</label>
<input type="text" required data-pristine-required-message="Please enter your name"
id="name" name="name" />
</div><!--/.form-group-->
<div id="recaptcha" data-size="invisible"></div>
<input id="submit" type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
</body>
</html>
<script>
var form = document.getElementById("contactForm");
// create the pristine instance
var pristine = new Pristine(form);
form.addEventListener('submit', function (event) {
event.preventDefault();
// check if the form is valid
var valid = pristine.validate(); // returns true or false
if(valid == true){
grecaptcha.execute(widgetId1);
}
});
</script>
Turns out the id doesn't refer to the css ID, it refers to an ID created when you use the render function.

one-time payment with Laravel Cashier without subscription

I'm Planning to use Laravel Cashier for one-time payments with Stripe. It says in the documentation:
If you're only performing "one-off" charges and do not offer subscriptions, you should not use Cashier.
However, I was able to charge the user without subscription using the following code:
$amount = $request['amount];
Stripe::setApiKey(Config::get('stripe.secret_key'));
$token = $input['stripeToken'];
$user = Auth::user();
return $user->charge($amount * 100, ['source' => $token]);
And it worked! I'm wondering is there a problem with this approach? Why they suggested to not use Cashier? Is it gonna cause problems along the way? Please let me know what do you think?
As currently implemented, it's safe to do this. You can see the code for the charge method here: https://github.com/laravel/cashier/blob/822b6535e755fd36dec8ecceb52cc8909c8a953e/src/Billable.php#L37
That said, given the explicit warning that Cashier isn't intended for this sort of use, it's your own fault if the charge function gets modified in a way that breaks your app somewhere down the line.
There's not much reason to use Cashier in this situation, either. Using the SDK's Stripe\Charge class directly will be cleaner code, and you don't take on the risk of misusing a different library.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<script src="https://js.stripe.com/v3/"></script>
<br><br>
<h1 align="center">One Time Charge</h1>
<form method = "post" action = "{{route('charge')}}" id="form">
#csrf
<div class="form form-cb" align="center">
Name on Card: <input type="text" id="card-holder-name" required>
<br> <br>
<div id="card-element" style="width: 300px;">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div><br>
<button disabled style="background-color:skyblue;color:black">$1.00 USD</button><br><br>
<button id="card-button" style="background-color: green;color:white;font-size:20px;" />Pay
</button>
</div>
</form>
<script>
var stripe = Stripe('Your Stripe-key');
var elements = stripe.elements();
var cardElement = elements.create('card');
cardElement.mount('#card-element');
// Add an instance of the card UI component into the `card-element` <div>
var cardHolderName = document.getElementById('card-holder-name');
var cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', async (e) => {
var { paymentMethod, error } = await stripe.createPaymentMethod(
'card', cardElement, {
billing_details: { name: cardHolderName.value }
}
);
if (error) {
console.log('error');
} else {
var payment_id = paymentMethod.id;
createPayment(payment_id);
}
});
var form = document.getElementById('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
});
// Submit the form with the token ID.
function createPayment(payment_id) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'payment_id');
hiddenInput.setAttribute('value',payment_id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
</body>
</html>

Combine client-side and server-side validation in Bootstrap 4 form

I have a Bootstrap 4 form with an input field, called runname. I want to perform the following validation on the input field:
runname cannot be empty
runname cannot contain spaces
runnamecannot already be used previously
I already have the code for a form which gives an error, using custom Bootstrap styles if the input field is empty:
// JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container">
<div class="col-md-12 order-md1">
<form class="needs-validation" novalidate method="post" action="#">
<div class="form-group row">
<label for="inputRunname" class="col-sm-2 col-form-label">Run name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputRunname" name="runname" placeholder="Run name" required>
<div class="invalid-feedback">
Please enter a run name
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
</body>
</html>
And I have some Javascript to check if an input contains spaces:
function cannotContainWhiteSpace(input, errorId, name) {
var value = input.value;
var errMsgHolder = document.getElementById(errorId);
if (!(/^\S*$/.test(value))) {
errMsgHolder.innerHTML =
'The ' + name + ' cannot contain whitespace';
input.focus();
return false;
}
}
And I also have some Python code on my Cherrypy backend which does a lookup in the database to see if the runname already exists:
try:
myConnection = mysql.connector.connect(host=self.database['host'], user=self.database['user'], passwd=self.database['passwd'], db=self.database['db'])
cursor = myConnection.cursor(buffered=True)
# unless overriden by the force flag, check whether the runname has already been used before
if not force:
reusedrunquery = "SELECT run FROM logs WHERE run = %s AND errormessage IS NULL"
cursor.execute(reusedrunquery, (runname,))
if cursor.fetchall():
flag = True
cherrypy.session['reusedRun'] = True
myConnection.close()
except mysql.connector.Error as err:
return self.database_failure(str(err))
But I don't know how to cobble all these different parts together to get a form where I have both the two client-side validations and the server-side validation.
On Submit event, you should have a method in your backend that actually intercepts the request and I think there you should be able to make a connection with your backend's logic.
Here they are the steps:
Form compiled correctly
Http POST request starts onSubmit event
Back-end receives the request and applies further logic by gathering the data on the method in charge to receive the Http POST request
Otherwise, you may try to make an AJAX call on which there will be executed the client-side validations and then it will call the server-side method/class for checking that runname has been used already.
Most of the times I use custom styles to achieve this.
.invalid-feedback{
display:none;
}
.invalid .invalid-feedback {
display:block;
}
<form novalidate>
<div class="form-group">
<label>Label</label>
<input class="form-control" name="runname" type="text">
<div class="invalid-feedback"></div>
</div>
</form>
In Javascript
Validate the input controls and set css classes and message text.In your case, validate not empty, no spaces, and not already used[server side].
If invalid add the class invalid to parent form-group, and set the validation message inside invalid-feedback div next to the input control.

Send method in new Vue is not called when form is submitted

<!DOCTYPE html>
<head>
<meta charset=" UTF-8">
<title> Document</title>
</head>
<body id="chat">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.5.0/socket.io.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script>
<form v-on="submit: send">
<input v-model="message">
<button>Send</button>
</form>
<script>
var socket = io();
new Vue({
el: '#chat',
date: {
message: ''
},
methods: {
send: function(e)
{
e.preventDefault();
alert("a");
}
}
})
</script>
</body>
I want to call the send method defined in new Vue when the form is submitted ,
But when i submit the form, page is reloading.
I have created a Vue object and linked it to the chat element.
I guess e.preventDefault() is not working.
Interesting, I just helped somebody with a similar issue, the syntax for Vue.2.0 is v-on:submit="send" not v-on="submit: send". Vue already has a way stop the form submitting which is: v-on:submit.prevent so you don't need the e.preventDefault, you would get:
<form v-on:submit="send" v-on:submit.prevent>
or a shorter version:
<form v-on:submit.prevent="send">
There are a few more issues here, so I will go through them for you:
Firstly, you are never submitting the form. To submit a form you need a submit input, not a button:
<input type="submit" value="Send" />
However, from what I can see it's likely you don't even need a form, and can simply use a button with v-on:click:
<div>
<input v-model="message">
<button v-on:click="send">Send</button>
</div>
And then get what was submitted from the view model:
send: function()
{
alert(this.message);
}
You should also use the console (under developer tools in your browser) and log any output rather than alert (console.log(this.message)), because it will also sniff out any general errors with your code - for example I can see that you also have a typo (the same one I always make) it's data not date:
data: {
message: ''
},
Okay, what about this
<form #submit.prevent="send">
<input v-model="message">
<button>Send</button>
</form>
And then you can remove preventing default browser action from your send() method

When using AJAX and php with Google Maps, page keeps refreshing

Good day all,
I have an html file as follows, which displays a Google Map (initialised at window.onload function) and has a form to enter the name of a place to search. When the submit button is clicked then user input is supposed to be sent to a php file which get the coordinates to display on the map. However, in testing, all the php file is returning right now is the same userinput.
The problem I am having, is that this sequence of event happens:
I enter some text, and click submit.
The p element innerHTML is changed and the alert appears (as in onreadystatechange function)
However, when i close the alert, the p element loses its data.
I added the alert, because when i just used
document.getElementById("msg").innerHTML=xmlhttp.responseText;
the p element took on its new data briefly before disappearing.
On thing i noticed was that while the alert was on the screen, the address bar displayed "filename.html". but when i closed it, and the p data disappeared, the address bar shows
filename.html?searchterm=user+input+stuff
Even when I click submit with the text input empty, I get "No Text Entered" appearing briefly, before the page "refreshes" then this text disappears, and the addressbar shows
filename.html?searchterm=
I appreciate any help I can get.
<html>
<head>
<title>Map</title>
<link rel="stylesheet" type="text/css" href="stylue.css" />
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?
key=AIzaSyBksQ7NlV6eXk6w5w8222lolqdPHsN_8ls&sensor=false">
</script>
<script type="text/javascript">
var panorama;
var map;
function initialize() {
//create Google Map
}
//other Google Maps functions
function searchdb(userInput){
var xmlhttp;
if (userInput==""){
document.getElementById("msg").innerHTML="No Text Entered";
}else{
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("msg").innerHTML=xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","searchpageajax.php?searchterm="+userInput,true);
xmlhttp.send();
}
}
window.onload= function () {
initialize();
}
</script>
</head>
<body >
<h1>Map</h1>
<p>Enter a room code or building name to search.</p>
<form name="inputform" >
<input type="text" name="searchterm" />
<input type="submit" value="Search" onclick="searchdb(searchterm.value)"/>
<input type="reset" value="Clear" />
<br/>
<p id ="msg"></p>
<br/>
</form>
<div id="container">
<div id="map_canvas"></div>
<div id="streetview_canvas"></div>
</div>
</body>
</html>
The page is refreshed because your onsubmit function does not return false.
See this post (there are probably others).

Resources