Submitting a form to an Angular 2 App - forms

What is the best way to submit a form to an Angular 2 app? I.e. from a non-angular website, to an Angular app?
You cannot simply put the app as the action URL with method="GET" as Angular 2 uses "matrix URL notation" and the browser will add the form fields as regular params (?= , &=).
For example this approach does not work, assuming the URL is an Angular 2 app:
<form method="GET" action="http://myangular2app.com/search;">
<input name="q">
<input type="submit" value="Go">
</form>
The browser will navigate to a URL like http://myangular2app.com/search;?q=mysearch when it needs to be http://myangular2app.com/search;q=mysearch (no question mark).

You can utilise two-way binding with use of the ngModel directive
<input name="q" [(ngModel)]='name'>
You will need to import the forms modules to utilise two-way binding; as well as the Http module for the request:
import { FormsModule } from '#angular/forms';
import { Http } from '#angular/http';
Use this for the call:
this.http.get("http://myangular2app.com/search;q="+mysearch)
If you are new to Angular2 I would recommend you spend a bit of time looking of the Angular2 tutorial 'Tour of Heroes'
This walks you through creating a simple web application involving (among other things) forms, data binding and HTTP requests

Related

Gorilla CSRF - Forbidden - CSRF token invalid - fails when there are two forms

I'm adding in CSRF token validation and I'm running into a problem where I have two forms on a page and one of them will submit successfully and the other will not. I'm not doing AJAX requests, I'm simply using hidden input fields. If I submit the form when it is the only one on the page, it submits without issue. If I submit it on a page with more than one form, it fails.
Below is the template code for my two forms
{{if .IsAuthenticated}}
<form action='/admin/logout' method='POST'>
<button>Logout</button>
{{.CsrfField}}
</form>
{{end}}
<form action='/admin/stuff/create' method='POST'>
{{with .Form}}
<div>
<label>Title:</label>
<input type='text' name='title' value='{{.Get "title"}}'>
</div>
<div>
<input type='submit' value='Publish stuff'>
</div>
{{end}}
{{.CsrfField}}
</form>
And this is what the generated HTML looks like. Both appear to be valid.
When I click the "Logout" button though, I get the Forbidden - CSRF token invalid error, but clicking the create input value in the second form always works.
The logout button is correctly validated when I attempt to use it on the home page which is "/admin/" but it does not work on any of the other pages "/admin/snippet/:id" or "/admin/snippet/create". The Logout button is part of a base template, so it appears on every page, so there shouldn't be anything different in how it appears on any page.
I've read other SO posts about multiple forms & CSRF tokens on a page and I understand there should be no issue with multiple forms with the same information as long as you have each one in it's own form, it should be fine. So I am not sure where I am going wrong.
I found the issue. Currently the way that gorilla/csrf works, it does not like creating the masked token from one path and then sending that token off to another path. So in my situation, going from /admin/snippet/create to /admin/logout threw an error because it was expecting the path for the token to be /admin/snippet/<something> and so it threw an error.
This issue has been addressed in this PR: https://github.com/gorilla/csrf/pull/147 and essentially the solution is to set the default path yourself to something which all of your routes will contain, so in my case that was /admin
This is what my CSRF declaration looks like now in main.go
var csrfMiddleWare = csrf.Protect(
[]byte("<put your 32 character key here>"),
csrf.Path("/admin"),
csrf.Secure(false),
)
A note, if you had this issue and then apply this fix and it doesn't resolve the problem, trying testing in a separate browser as there may be some caching issues.

Can i use ngxErrors or something like it to display a form error?

I use ngxErrors to display errors for a form control and it works great. Is there any way to get similar functionality for a form or a form group? Currently, I display a form error like this:
<div *ngIf="form.hasError('loginFailed')">
Login Failed
</div>
The bummer is, when I detect that there is a form error (e.g. after the login form is submitted) as opposed to control error, I set it like this:
this.form.setErrors({ loginFailed: true });
this.cdr.detectChanges();
Where this.cdr is an instance of ChangeDetectorRef. This is necessary because I'm using OnPush change detection strategy. So basically it's like calling $scope.$apply() from AngularJS all over again.
What I would really like to do is something more like how ngxErrors does it:
<div ngxErrors="myForm">
<div ngxError="loginFailed" [when]="['dirty', 'touched']">
The login has failed
</div>
But ngxErrors expects myForm to be a control.
This feature is not currently baked into ngxErrors, but I submitted a PR. https://github.com/UltimateAngular/ngxerrors/pull/18
The working syntax is a slight modification of the above:
<div ngxErrors>
<div ngxError="loginFailed" [when]="['dirty', 'touched']">
The login has failed
</div>
</div>
I learned that you do not have to tell child components the form, the FormGroupDirective is available to children automatically.
See this library https://www.npmjs.com/package/ng-error-messages for show error messages based on validation rules:
<input placeholder="Texto:" formControlName="text">
<div errorMessage="text" alias="Super Texto" ></div>

jquery mobile and knockout form submit binding

I stumbled on an apparent incompatibility between knockoutjs and jquery mobile when it comes to form submit behavior.
Consider the following markup:
<form data-bind="submit: myKoSubmitAction">
<!-- form fields here -->
</form>
The intention is that knockout prevents server post/get and instead calls myKoSubmitAction. jqm will also prevent standard submit behavior only for jqm the reason is that the form submit is replaced by an ajax request.
So while knockout (presumably) succeeds at preventing the standard server request, it fails to prevent jqm from sending an ajax request.
I found the answer to this problem in a google group and thought it should be on SO as well. See below
You can also add data-ajax="false" to the <form> element.
See Submitting Forms.
The best solution I have been able to find is the following custom ko binding:
//This binding fixes apparent incompatibility between knockout and jqm
ko.bindingHandlers.jqmsubmit = {
init: function (el, accessor, allbindings, vm) {
ko.bindingHandlers.submit.init(el, accessor, allbindings, vm);
$(el).submit(function (e) {
// prevent the submit behavior
e.preventDefault();
e.stopPropagation();
return false;
});
}
};
To be used in the place of the standard submit ko binding:
<form data-bind="jqmsubmit: myKoSubmitAction">
<!-- form fields here -->
</form>

How to add a contact form to a static web site?

I have a mostly "static" web site with no server-side code and just a little JavaScript. Now I would like to add a contact form. I do not care how I get the contact form data (so just writing this data to a text file in the server will be ok).
What is the simplest solution for this problem? How do people usually handle this?
I believe I can add some server-side code (PHP or something) to handle the form (and write the form data to a file, for instance) but I would prefer a client-side solution.
Use an external tool, they are commonly referred to as "formmailer". You basically submit the form to their server, and they send the form contents via mail to you.
If you don't want that, you have to do something server-sided: Storing data on the server, without having a server side program that accepts the data from the client, is just not possible.
You could install CouchDB and interface that from Javascript :) Everyone could use that then, too :)
The most easy PHP script that stores POST data on your harddisk:
<?php file_put_contents('/path/to/file', serialize($_POST) . "\n", FILE_APPEND); ?>
You can use Google Drive and create form with required fields. and embed code (which will be iframe) in your static web page.
You will be able to get submitted data in spreadsheet.
You can use qontacto . it is a free contact form you can add to any website. it forwards you the messages.
I set up the fwdform service for this exact need.
Just two simple steps to get your form forwarded to your email.
1.Register
Make an HTTP POST request to register your email.
$ curl --data "email=<your_email>" https://fwdform.herokuapp.com/register
Token: 780a8c9b-dc2d-4258-83af-4deefe446dee
2. Set up your form
<form action="https://fwdform.herokuapp.com/user/<token>" method="post">
Email: <input type="text" name="name"><br>
Name: <input type="text" name="email"><br>
Message: <textarea name="message" cols="40" rows="5"></textarea>
<input type="submit" value="Send Message">
</form>
With a couple of extra seconds you can spin up your own instance on Heroku.

Python3 How would I log in Facebook using requests

<input type="text" class="inputtext" name="email" id="email" value="" tabindex="1"> is the email box
<input type="password" class="inputtext" name="pass" id="pass" tabindex="2"> is the password box
<input value="Connexion" tabindex="4" type="submit" id="u_0_v">
is the submit button
Now... I have this script running but I still can't manage to login ( I get to the same login page: facebook.com)
import requests
from bs4 import BeautifulSoup
body = {'email':'xxxx#hotmail.com','pass':'xxxxx',}
con = requests.post('https://www.facebook.com', data=body)
s = BeautifulSoup(con.content)
print (s)
Do I have to pass in the 'submit button' in the body{}. I thought I should include it but there is no name for the submit button so I don't know how to include it in the body{}. Thanks for the help
You always need to pay attention to any additional (hidden) fields, that are sent along credentials, and might be needed for any server processing.
That is the case for your example with runescape.com. When you use your browser to intercept data, that is normally being sent along with the form, you can modify the script in this manner:
import requests
from bs4 import BeautifulSoup
body = {'username':'xxxx#hotmail.com','password':'xxxxx','submit':'Login','mod':'www','dest':'community'}
con = requests.post('https://secure.runescape.com/m=weblogin/login.ws', data=body)
s = BeautifulSoup(con.content)
print(s)
You can see mod and dest parameters were needed to make the server processing function. As for the submit button, it is rarely checked for, but it is always safer to include it as well (as I did in this example).
The result is not 404 anymore, but the login will nevertheless fail, as there is Captcha in place to prevent automatic login.
As for Facebook, there are a lot of complicated supplementary fields, that would require a lot of reverse engineering to be done. I would strongly suggest to consider using the official Facebook Graph API (https://developers.facebook.com/docs/graph-api) if possible to accomplish what you need.