post user and password from website in Flutter - html

I want to use information from a website in an app I programm in flutter. I need to log in at the website first. The html code of the website is this:
<div>Geben Sie Ihren Benutzernamen und Ihr Passwort ein, um sich an der Website anzumelden:</div>
<!-- ###LOGIN_FORM### -->
<form action="/fuer-studierende/intranet/" target="_top" method="post" onsubmit="; return true;">
<fieldset>
<legend>Anmelden</legend>
<div>
<label for="user">Benutzername:</label>
<input type="text" id="user" name="user" value="" />
</div>
<div>
<label for="pass">Passwort:</label>
<input type="password" id="pass" name="pass" value="" data-rsa-encryption="" />
</div>
I need to fill in the user name in line 8 after "value" and the password in line 12 after "value". How can I do this in flutter?

You have to use flutters WebView package to send data from Flutter to HTML using JavaScript.
Follow this short tutorial to get a quick overview off the WebView package:
https://medium.com/flutter/the-power-of-webviews-in-flutter-a56234b57df2
If you assign a WebViewController to the WebView (see tutorial) you can use the controller to send JavaScript messages to the HTML webpage from Flutter.
Use the following code in the «onPageFinished» function of the WebView widget:
_webController.evaluateJavascript(
'''
var email = document.getElementById("user");
var password = document.getElementById("pass");
email.value = "${_yourFlutterUserTextController.text}";
password.value = "${_yourFlutterPasswordTextController.text}"
'''
);
As you can see you can place Flutter variables like the username and password from your Flutter app and send the JavaScript snippet to the website which executes the JavaScript.
You could also fire a button click after filling out the login...
Hope this helps and good luck!

When you fill in those fields in a browser and hit submit the browser sends a request to the action url, using the method specified in the form tag. If the method is POST it collects the fields, encodes them using a format called x-www-form-urlencoded and adds that as the body of the request.
(Note that the browser may take some additional steps like running JavaScript, which may alter the values. You would need to alter your values in the same way.)
The Dart package:http provides all these functions for you. If you provide a Map<String, String> as the body parameter of a post, it encodes them for you and sets the content type.
void send() async {
var form = <String, String>{
'user': 'miwa',
'pass': 'M1VVA%',
};
var res = await http.post(
'https://some.website.de/fuer-studierende/intranet/',
body: form,
);
print(res.statusCode);
print(res.body);
}
Of course, you will likely receive in response a large lump of HTML and a session cookie, which you will have to parse and extract respectively.

Related

How to send html form data to another web server via a button click

I have two web servers. One running my front-end (example.com), one running my back-end (api.example.com).
On my front-end (example.com) I have this code which is a simple html website that has a form, with an input field and a button. When I click the button I'd like to get that data and send it to the back-end (api.example.com). For example, I put 'nathan' in the username field of the front end and click the button. I want it to send me to api.example.com/sendcode?username=nathan
I currently have this code, but the button is keeping me on the same website, instead of doing to a completely different url:
<form class="login100-form validate-form flex-sb flex-w" action="api.example.com" method="POST">
<span class="login100-form-title p-b-51">
Request for a code
</span>
<div class="wrap-input100 validate-input m-b-16" data-validate = "Username is required">
<input class="input100" type="text" name="username" placeholder="Username">
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn m-t-17">
<button class="login100-form-btn">
Send code
</button>
</div>
<div class="flex-sb-m w-full p-t-3 p-b-24">
<div class="contact100-form-checkbox">
</div>
</div>
</form>
With this code it's sending me to 'example.com/api.example.com?username=nathan' How would I fix this, would like to keep the two completely different?
You need a fully qualified URL with protocol - preferably https, as in action="https://api.example.com/sendcode"
Please search for AJAX and your server process. Alternatively use fetch
const username = document.querySelector("[name= username]").value;
fetch('https://api.example.com/sendcode?username='+encodeURIComponent(username))
.then(response => response.json())
.then(data => console.log(data));
To use Ajax, you need to grab the submit event
Here I use jQuery for speed of coding an example, just include <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> in the page to use it
$(".login100-form").on("submit", function(e) {
e.preventDefault(); // stop submit
$.post('https://api.example.com/sendcode',
{ data : $(this).serialize() }, // the form content in key=value format
function(response) {
console.log(response)
})
})
Change your form action to include http:// e.g.
<form class="login100-form validate-form flex-sb flex-w" action="http://api.example.com" method="POST">
There could be numerous methods depending upon scenarios but simplest of all which might expose data in querystring is sending a post request on button click through a simple javascript method.

HTML input must contain a specific string

I have a input field, which will record the response of the end-user. Say the label of it is Linkedin URL. The user who has to enter the linkedin URL could enter some other input(facebook.com/satyaram2k14), which is not invalid. So how can one check, if the url entered contains string 'linkedin.com' along with other text. Final url should be 'linkedin.com/satyaram2k14'. How can I check for this pattern at front-end.
There are several approaches you can take:
Rely on the HTML5 form validation via required and pattern attributes
Validate the input value via JavaScript on form validation
Optionally provide a visual hint on the (in)valid state of the field content
HTML5 validation works in any modern browser and integrates into the browser UI (including localisation of error messages). But it's not as flexible and the helpfulness of the error message given when the pattern does not match varies from browser to browser.
In any case, you should always validate user input on the server side as well, because any client validation can be circumvented.
Here are some code examples of all three approaches. They all use the RegEx pattern ^https?://(www\.)?linkedin\.com, so they'll allow http or https protocol and urls with or without "www.".
var form = document.getElementById('form');
var field = document.getElementById('url');
var fieldstatus = document.getElementById('fieldstatus');
var regExPattern = new RegExp('^https?://(www\.)?linkedin\.com', 'i');
// validation on form submit
form.addEventListener('submit', function(ev) {
if (!regExPattern.test(field.value)) {
ev.preventDefault();
alert('The input value does not match the pattern!');
}
});
// validation on input
field.addEventListener('input', function() {
if (!regExPattern.test(field.value)) {
fieldstatus.innerHTML = 'invalid';
} else {
fieldstatus.innerHTML = 'valid';
}
});
<h1>HTML5 validation pattern</h1>
<form>
<input type="text" pattern="^https?://(www\.)?linkedin\.com" required /><br>
<input type="submit" />
</form>
<h1>Custom JavaScript validation</h1>
<form id="form">
<input type="text" id="url" /> <span id="fieldstatus">invalid</span><br>
<input type="submit" />
</form>
One quick way of doing this is by using the pattern attribute of input, like so:
<input type='text' pattern='^linkedin\.com/'>
^linkedin\.com/ being a regular expression that matches all strings that start with linkedin.com/.
Using this attribute, the browser by itself will only accept such strings.

How can I use user and password variables in my json request?

Pic 1: Angular 4
In the first picture I have my user input and I can display in the console variables username and password. In the second picture I am sending username and password with my token. How can I use the username and password from first picture and send those with my header? Please help.
Pic 2: json request
Headers class is constant so when you use it only is possible set headers while you are using new statement. i.e.
new Headers({header:value})
new Headers().append('header', 'value');
However this not work because is a constants
let headers = new Header();
headers.append('header','value')
You only can do thing as
new Headers({header:btoa(userna + ':' + password)});
HTML
<form #myForm="ngForm" (submit)="onSubmit(myForm)">
<input type="text" name="username">
<input type="password" name="password"
<input type="submit" value="Submit">
</form>
COMPONENT
onSubmit(form) {
if(form.valid) {
console.log(form.control.username);
console.log(form.control.password);
}
}
Ok if you are looking for your logins data, le proper way is to emit an event like this :
login-form component:
#output
onLogin : EventEmitter<any> = new EventEmitter();
login(e){
***
this.onLogin.emit({username:username,password:password});
}
app component.html
<login-form (onLogin)="getData($event)"></login-form>
here "$event" represent your object "{username:username,password:password}";
otherwise you can store datas in a variable and run "getData" when you want.
Other suggestions:
Use angular reactive-forms like this :https://angular.io/guide/reactive-forms#add-a-formgroup
maybe run your xhr from angular services.

How to send credit card form data to a finance companies by using their node app

Html (unnecessary details removed) will publish at firebase, and php is not working.
<form id="kkDetay" name="kkCek" method="post">
<input type="text" id="name-on-card" placeholder="Name Surname">
<input type="text" id="card-number" placeholder="Card Number">
<input type="text" id="card-exp-month" placeholder="Month">
<input type="text" id="card-exp-year" placeholder="Year">
<input type="text" id="card-cvc" placeholder="Cvc">
<button id="subm2" type="submit">Pay Now</button>
</form>
Company https://github.com/iyzico/iyzipay-node and company node sample: in senddata.js (below)
var Iyzipay = require('iyzipay');
var iyzipay = new Iyzipay({
apiKey: 'sandbox-PZ8jicWrEeE1rt1O75FTOegr5lsW3xxx',
secretKey: 'sandbox-2Q6aaP1FK3HFrXkTsHfftxfiudFMfxxx',
uri: 'https://sandbox-api.iyzipay.com'
});
var request = {
locale: Iyzipay.LOCALE.TR,
conversationId: '123456789',
price: '1',
paidPrice: '1.2',
currency: Iyzipay.CURRENCY.TRY,
installment: '1',.........................
.....................................
datas to send (full list at above link)
}
iyzipay.payment.create(request, function (err, result) {
console.log(err, result);
done();
});
Now, when I use at Command prompt> node senddata.js its working sending dummy datas.
How to connect and send form data to this senddata.js and run it at firebase server.
You cannot run your own server-side code on Firebase.
To use that Node code that you gave as an example you would have to write a Node server, e.g. using Express, Hapi, Restify, LoopBack or some other framework, run it on some server, listen to requests and process them using the example code that you showed.
You HTML from would need to send the data to your Node server.
Keep in mind that you have to use HTTPS connection for that. Never send sensitive data such as names or credit card numbers unencrypted. I would not advise you do to it if you don't know what you're doing.
You may have a better luck integrating Stripe with Firebase because there are tutorials online. Also it's better to use a credit card service lie Stripe even if you're doing your own backend because with Stripe you don't actually process the credit card numbers yourself so there are less legal implications.

Create a basic MailChimp signup form using their API

I'm new to MailChimp and need some help.
With their basic newsletter signup form... you simply embed some prepackaged HTML into your page. However the problem with this is that clicking on submit redirects to a MailChimp page. (I don't want to redirect to MailChimp, I want the user to stay on own website after hitting submit.)
They provide an API and plenty of documentation but just about zero useful examples. The API is supposed to allow me to do a full integration with my site or application. It seems that when I read something in their docs that applies to me, I click the link to get more information and I end up going around in circles. They tell you how to do it but they fail to "show" you how to it.
I can get an API Key, they have tons of documentation, and a whole bunch of wrappers & plugins... PHP, Drupal, Wordpress, etc...
The confusion here regarding their pre-packaged solutions is that I just have a regular static HTML page, it's not Wordpress, PHP, or Drupal... so I just don't know where to start ... I don't even know if I'm supposed to use POST or GET.
I'm not a newbie to API's... I do very well with getting the Google Maps API to do whatever I want. However, Google provides real-world working examples in addition to their detailed documentation which is how I learned it. I just want to see it in action before I can grasp the finer points of the API.
Without any solid examples or tutorials in their online documentation, I'm asking how to create the most basic HTML signup form using their API.
EDITED:
Since posting this answer MailChimp has released version 2 & 3 of their API. Version 3 will be the only supported version starting in 2017. As soon as I have a chance to test it, I will update this answer for API version 3.
MailChimp API v3.0
As per notification at the top of this page, all prior versions of the API will not be supported after 2016.
My solution uses PHP in the background for handling the API, and jQuery to facilitate the Ajax.
1) Download a PHP wrapper that supports API v3.0. As of this writing, there is nothing official listed in the latest MailChimp docs that supports v3.0, but several are listed on GitHub, so I selected this one.
2) Create the following PHP file, store-address.php, using your own API key and list ID, and then place it in the same directory as the wrapper from step one. Remember to follow the documentation for your wrapper, but they all seem fairly similar to this.
<?php // for MailChimp API v3.0
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
function storeAddress() {
$key = "xxxxxxxxxxxxxxx-us1";
$list_id = "xxxxxx";
$merge_vars = array(
'FNAME' => $_POST['fname'],
'LNAME' => $_POST['lname']
);
$mc = new MailChimp($key);
// add the email to your list
$result = $mc->post('/lists/'.$list_id.'/members', array(
'email_address' => $_POST['email'],
'merge_fields' => $merge_vars,
'status' => 'pending' // double opt-in
// 'status' => 'subscribed' // single opt-in
)
);
return json_encode($result);
}
// If being called via ajax, run the function, else fail
if ($_POST['ajax']) {
echo storeAddress(); // send the response back through Ajax
} else {
echo 'Method not allowed - please ensure JavaScript is enabled in this browser';
}
3) Create your HTML/CSS/JavaScript(jQuery) form (It is not required to be on a PHP page, and the visitor will never see that PHP is being used in the background.)
The response is in JSON so you'll have to handle it correctly.
Here is what my index.html file looks like:
<form id="signup" action="index.html" method="get">
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("Adding your email address...");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
type: 'POST', // <- IMPORTANT
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
var message = $.parseJSON(msg),
result = '';
if (message.status === 'pending') { // success
result = 'Success! Please click the confirmation link that will be emailed to you shortly.';
} else { // error
result = 'Error: ' + message.detail;
}
$('#message').html(result); // display the message
}
});
return false;
});
});
</script>
MailChimp API version 1:
(original answer)
After fumbling around for a while, I found a site using the PHP example with jQuery. From that I was able to create a simple HTML page with jQuery containing the basic sign-up form. The PHP files are "hidden" in the background where the user never sees them yet the jQuery can still access & use.
1) Download the PHP 5 jQuery example here... (EDIT: links are dead. However, the only important part is the official API wrapper for PHP which is available HERE.)
http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip
If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.
http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip
2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.
3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.
Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:
<?php
function storeAddress() {
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('123456789-us2');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "123456a";
if ($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype'])) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a confirmation link.';
} else {
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']) {
echo storeAddress();
}
4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.
Here is what my index.html file looks like:
<form id="signup" action="index.html" method="get">
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
Text: <input type="radio" name="emailtype" value="text" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("Adding your email address...");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
Required pieces...
index.html constructed as above or similar. With jQuery, the appearance and options are endless.
store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.
MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.
Here is an example using version 2.0 of Mailchimp API together with mailchimp-api (a minimal php abstraction class for dealing with the Mailchimp API).
<?php
include('MailChimp.php');
$MailChimp = new MailChimp('API_KEY');
$result = $MailChimp->call('lists/subscribe', array(
'id' => 'LIST_ID',
'email' => array( 'email' => $_POST['email'] ),
'merge_vars' => array(
'MERGE2' => $_POST['name'] // MERGE name from list settings
// there MERGE fields must be set if required in list settings
),
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false
));
if( $result === false ) {
// response wasn't even json
}
else if( isset($result->status) && $result->status == 'error' ) {
// Error info: $result->status, $result->code, $result->name, $result->error
}
?>
Read more about what you can send with the API call at the MailChimp API Documentation.
Here's another example of using version 2.0 of the Mailchimp API using the Official PHP Wrapper.
The difference between my example and others posted here is that I'm using the subscribe method of the Mailchimp_Lists class, accessible through instantiation of the Mailchimp class (->lists), rather than the generic call method.
$api_key = "MAILCHIMP_API_KEY";
$list_id = "MAILCHIMP_LIST_ID";
require('Mailchimp.php');
$Mailchimp = new Mailchimp($api_key);
$subscriber = $Mailchimp->lists->subscribe($list_id, array('email' => $_POST['email']));
if ( ! empty($subscriber['leid'])) {
// Success
}