Angularjs - simple form submit - javascript

I am going through learning curve with AngularJs and I am finding that there are virtually no examples that serve real world use.
I am trying to get a clear understanding of how to submit a form with the most standard components and pass it on to a PHP file..
My fiddle.
Does anyone have any good examples on submitting simple, un-polluted, forms that would help me and probably numerous other Angularjs beginners..
When I say a clean form I am referring to something like this..
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" ng-model="form.firstname"> <br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress"> <br/><br/>
<textarea rows="3" cols="25" ng-model="form.textareacontent"></textarea>
<br/><br/>
<input type="radio" ng-model="form.gender" value="female" />Female ...
<input type="radio" ng-model="form.gender" value="male" />Male <br/>
<br/><br/>
<input type="checkbox" ng-model="form.member" value="5"/> Already a member
<br/><br/>
<input type="file" ng-model="form.file_profile" id="file_profile"><br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<!-- <button ng-click="save()" >Save</button> -->
<input type="submit" ngClick="Submit" >
</form>
</div>
My ng-app code...
var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
var formData = {
firstname: "default",
emailaddress: "default",
textareacontent: "default",
gender: "default",
member: false,
file_profile: "default",
file_avatar: "default"
};
$scope.save = function() {
formData = $scope.form;
};
$scope.submitForm = function() {
console.log("posting data....");
formData = $scope.form;
console.log(formData);
//$http.post('form.php', JSON.stringify(data)).success(function(){/*success callback*/});
};
});
I guess three questions I have from here on are...
How is my php file supposed to interact with this (how to I get the json string to an array in php file)?
How would I submit value of a checkbox when the checkbox is true?
I find a lot of information abotu using jQuery with Angular to submit images,, I see there is an image object in this submission already,, how do I retrieve that data? What are considerations to include with images?
I am willing to take any clear and concise information and assemble a good learning example for everyone...
My fiddle

WARNING This is for Angular 1.x
If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.
ORIGINAL ANSWER
I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" name="form.firstname">
<br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress">
<br/><br/>
<textarea rows="3" cols="25">
Describe your reason for submitting this form ...
</textarea>
<br/>
<input type="radio" ng-model="form.gender" value="female" />Female
<input type="radio" ng-model="form.gender" value="male" />Male
<br/><br/>
<input type="checkbox" ng-model="form.member" value="true"/> Already a member
<input type="checkbox" ng-model="form.member" value="false"/> Not a member
<br/>
<input type="file" ng-model="form.file_profile" id="file_profile">
<br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<input type="submit">
</form>
</div>
Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission.
Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission
BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.
For general advice on angular form submission see the cookbook examples
UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission
The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.
Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.

Sending data to some service page.
<form class="form-horizontal" role="form" ng-submit="submit_form()">
<input type="text" name="user_id" ng-model = "formAdata.user_id">
<input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>
$scope.submit_form = function()
{
$http({
url: "http://localhost/services/test.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
$scope.status = status;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:
Angularjs - Form Post Data Not Posted?
The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().
If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

var app = angular.module( "myApp", [] );
app.controller( "myCtrl", ["$scope", function($scope) {
$scope.submit_form = function(formData) {
$scope.formData = formData;
console.log(formData); // object
console.log(JSON.stringify(formData)); // string
$scope.form = {}; // clear ng-model form
}
}] );
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="submit_form(form)" >
Firstname: <input type="text" ng-model="form.firstname" /><br />
Lastname: <input type="text" ng-model="form.lastname" /><br />
<hr />
<input type="submit" value="Submit" />
</form>
<hr />
<p>Firstname: {{ form.firstname }}</p>
<p>Lastname: {{ form.lastname }}</p>
<pre>Submit Form: {{ formData }} </pre>
</div>
Codepen

Related

HTML post form not worked when migrated to Angular

I am doing a POST request using an HTML form, I copied the same form content to a new blank Angular project and it didn't work and throws an error. Does Angular process forms in a different way?
Actually, what the HTML/JS file is doing is to post form content to a URL (by sending a unique generated hash and some other information), upon success it will redirect to the correct page, otherwise, it will throw an error.
Unfortunately, the backend doesn't support sending a JSON request to it, but only a form.
The code snippet for the HTML form:
<form name="formpaiement" Id="formpaiement" action="https://testpayment.cmi.co.ma/fim/est3Dgate" method="post">
<input type="hidden" name="hashAlgorithm" value="ver3">
<input type="hidden" name="encoding" value="UTF-8">
<input type="hidden" name="TranType" value="PreAuth">
<input type="hidden" name="currency" value="504">
<input type="hidden" name="amount" value="1">
<input type="hidden" name="CallbackResponse" value="true">
<input type="hidden" name="BillToCountry" value="MA">
<input type="hidden" name="storetype" value="3D_PAY_HOSTING">
<input type="hidden" name="failUrl" value="https://testpayment.cmi.co.ma/fim/est3dteststoreutf8?pagelang=en">
<input type="hidden" name="clientid" value="80000xxxx">
<input type="hidden" name="okUrl" value="http://cmiecom.dx.am/ok.php">
<input type="hidden" name="lang" value="en">
<input type="hidden" name="MERCHANTSAFE" value="MERCHANTSAFE" />
Token : <input type="Text" name="MERCHANTSAFEKEY" value="ABC123">
<input type="hidden" name="MERCHANTSAFEAUTHTYPE" value="3DPAYAUTH">
<input type="hidden" name="MERCHANTSAFEACQUIRER" value="60">
<input type="hidden" name="MERCHANTGROUPID" value="60029">
<input type="hidden" name="hash" value="hash">
</form>
<input type="submit" value="valider" onclick="document.formpaiement.submit()">
Link to the working HTML file
Link to the Angular project (you may notice that's not the best way to submit form content, but, just for demo purposes, it will look similar to the above HTML file).
I'm guessing the problem is how you've defined the hash field in you form. In the plunker that generates the error, you're sending undefined as the value for the hash field. In the stackblitz example that works there's an actual value.
Here's what your form data looks like in the plunker:
And here's what the stackblitz sends:
In your working example, you have an onclick event that appears to compute the value for "hash", append it to the form and then submit it. Snippet taken from the stackblitz:
function submitformpaiement() {
hashval = "";
// compute value for "hashval" (removed for brevity)
$('<input />').attr('type', 'hidden').attr('name', "hash").attr('value', hash).appendTo('#formpaiement');
document.formpaiement.submit();
}
<input type="submit" value="valider" onclick="submitformpaiement();">
In your Angular version, you've added the hash field and bound the value to something that doesn't exist (hence undefined). Your onclick event also doesn't execute any function, it just submits the form.
<form name="formpaiement" Id="formpaiement" action="https://testpayment.cmi.co.ma/fim/est3Dgate" method="post">
<!--lots of inputs (removed for brevity) -->
<!-- "hashCMI" doesn't exist!! -->
<input type="hidden" name="hash" [value]="hashCMI">
</form>
I suspect you need to make sure you generate a value for hash before actually submitting.
Angular has a very specific way of working with forms (https://angular.io/guide/forms-overview), and a very specific way of working with web services (https://angular.io/guide/http). Unfortunately, just having the form in the template is not going to work - you might as well not use Angular at all if that's your intention.
But that is not the only problem.
Looking at your two examples, what you have on Stackblitz describing as the "HTML example" vs. on Plunkr with Angular are not doing the same thing, so you can't compare one to the other.
In your Stackblitz example, there is a whole bunch of javascript that's executed prior to the form being submitted. If I change your example to do the same thing that your Angular example is doing, you get the same exact result as the Angular error. Here's the comparable "just HTML" example: https://stackblitz.com/edit/web-platform-2gvw46
So the solution is to make sure your Angular application is doing the same exact logic as your original Stackblitz example, and does it in an Angular way (you can't copy/paste the JavaScript from the other example and expect it to work).

google apps script sidebar form Send button not working

I'm creating a google add on for sheets. The sidebar I'm working on is intended to be sort of help ticket submission, but way before I can develop that part of things, I'm not getting the submit button in the form to call the javascript function I want to build.
I've removed all of the form data from the html button call to activate a Logger.log. No dice.
I created a completely separate (and very simple) button to call a different function to call Logger.log. This also did not work.
I've double checked the form data, the send call, and the function.
I made sure the name of the function (sendMsg) is unique.
I think that the issue may not be in my code but in some other way the html and javascript (.gs) are connected.
here is the html form:
<div class="block form-group">
<form>
<label for="reason">Purpose of Contact</label>
<select id="reason">
<option selected>Help Request</option>
<option>Feature Request</option>
<option>Error Report</option>
<option>Other</option>
</select>
<label for="email">Email</label>
<input type="text" id="email" style="width: 200px;">
<label for="phone">Phone</label>
<input type="text" id="phone" style="width: 120px;" value = "optional">
<br>
<label for="translated-text">
<b>Message</b></label>
<textarea id="userMsg" rows="15" cols="35">
</textarea>
<br>
<input id="app" name="appSrc" type="hidden" value="COE">
<input type="button" class="action" name="helpRequest" value="SEND" onClick="google.script.run.sendMsg(
document.getElementById('reason').value,
document.getElementById('email').value,
document.getElementById('phone').value,
document.getElementById('userMsg').value,
document.getElementById('appSrc').value
)" />
</form>
</div>
and here is the function called:
function sendMsg(appSrc,reason,email,phone,userMsg) {
appV = appSrc;
reasonV = reason;
emailV = email;
phoneV = phone;
userMsgV = userMsg;
Logger.log('cheese');
}
Right now the form should simply result in a Logger.log message. At this point nothing happens.
In your situation, when "SEND" button is clicked, the script of sendMsg() at Google Apps Script side doesn't work.
You want to run sendMsg().
If my understanding is correct, how about this modification?
Modification point:
When I saw <input id="app" name="appSrc" type="hidden" value="COE">, appSrc is not id. By this, an error occurs at document.getElementById('appSrc').value, and sendMsg() didn't work. So if your script is modified, for example, please use app.
From:
document.getElementById('appSrc').value
To:
document.getElementById('app').value
Or
From:
<input id="app" name="appSrc" type="hidden" value="COE">
To:
<input id="appSrc" name="appSrc" type="hidden" value="COE">
If I misunderstood your question and this was not the result you want, I apologize.
In case anyone has the same issue as I had... onpress doesn't seem to work here. I had to change it to onclick.

How to reset the form data in html using jquery/javascript && and also how to send the form data to an email using jquery?

I'm new to jquery
I'm working on a form data html,
now i need to reset the data on click on the reset button and also need to transfer the form data to email on click on submit button.
Can anyone help me in solving this??
Before Posting the question I have gone through the link which Pierre C. has updated and my question is different from that question and even how to add /can we add "type" attribute in anchor tag.??
here is the html:
<form id="form" method="post">
<fieldset>
<label>
<input type="text" value="Name">
</label>
<label>
<input type="text" value="Email">
</label>
<label>
<input type="text" value="Phone">
</label>
<label>
<textarea>Message</textarea>
</label>
<div class="btns">
Clear
Send
</div>
</fieldset>
</form>
To clear all the data within a form, all you have to do is add an
<input type="reset" name="reset" value="Reset"></input>
However, reset buttons are annoying and no one ever uses them, so I suggest you just leave that. With regards to sending the form, the way I would do it is write this app in ASP.NET MVC and just put the mail logic in the controller, or create an API for your app, then create an Ajax POST on the button click using the form data as API parameters.

Submitting JSON struct to MailChimp API via HTML form + JavaScript

Appreciate your help on what I'm sure is a real basic head-slapper. I'm setting up a simple web front-end so that I can check if an email address is already a subscriber to an existing MailChimp list. For now I'd like to just use basic HTML & JavaScript.
My MailChimp API Key checks out, and I can run queries that only require string data, but the relevant API call requires a struct for email address(es), and I keep getting an error in any variation of the code below. I've gone as far as installing node.js and just running that from the command line and the query does work with the same data, so I'm sure I'm just this close, but need your help to get over the hump.
Here is the relevant snippet of the script and form. As written, I receive the following error message in reply: Validation error: {\"email\":\"Please enter a struct\/associative array\"}"}
<script type="text/javascript">
function collectAndSubmit() {
var emailAddy = document.getElementById("emailAddy").value;
var JSONemail = {"email":
{
"email": emailAddy
}
};
document.getElementById("email").value = JSONemail;
document.getElementById("apikey").value ="M*Y*A*P*I*K*E*Y"
document.testform.submit();
}
</script>
</head>
<body>
<form action="https://us2.api.mailchimp.com/2.0/helper/lists-for-email" method="post" name="testform">
Email Address: <input type="text" id="emailAddy" name="emailAddy" />
<input type="hidden" id="apikey" name="apikey" />
<input type="hidden" id="email" name="email" />
<br>
<input type="button" value="Check Email" onclick="collectAndSubmit()" />
</form>
</body>
</html>
Thanks in advance for your help.
Your form is incorrect. You can take a look at their documentation. You have to setup what they call an email struct which is really an array. Your email input attribute should look like <input type="text" id="email" name="email[email]">.
Notice the email[email] it will make the data look like "email": {"email": "input value"}
Also if your api key is supposed to be a secret then placing it hidden in the html form is not a good idea.

why this dijit.form doesnt submit?

Why this form wont submit?
<div data-dojo-type="dijit/form/Form" id="myForm" data-dojo-id="myForm"
encType="multipart/form-data" action="Cart.php" method="post">
<input type="text" name="searchName"
data-dojo-type="dijit/form/TextBox"
data-dojo-props="trim:true, propercase:true" id="searchName" />
<input type="radio" data-dojo-type="dijit/form/RadioButton" name="sl" id="radioOne" value="full"/> <label for="radioOne">Full</label>
<input type="radio" data-dojo-type="dijit/form/RadioButton" name="sl" id="radioTwo" value="short"/> <label for="radioTwo">Short</label>
Data Select
<select name="select1" data-dojo-type="dijit/form/Select">
<option value="2">Data1</option>
<option value="1">Data2</option>
</select>
<button data-dojo-type="dijit/form/Button" type="submit" name="submitButton" value="Submit">Submit</button>
</div>
Some javascript too:
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.8/dojo/dojo.js" data-dojo-config="parseOnLoad:true"></script>
<script type="text/javascript">
dojo.require("dijit.form.Form");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TextBox");
dojo.require("dijit/layout/AccordionContainer");
dojo.require("dijit/layout/BorderContainer");
dojo.require("dijit/layout/ContentPane");
</script>
Maybe its a stupid question, but ive been looking at it several hours and still cant figure it out.
Thanks in advance
I'm not sure what do you meet by won't submit. I moved your code into JS Bin (http://jsbin.com/iziwen/1/edit) and it works fine:
If you experience problems on the server side I suggest you change encType="multipart/form-data" to enctype="application/x-www-form-urlencoded" (or do not use it at all as it is the default value) - you do not need multipart/form-data, you are not sending files (see more here).
If this won't help, please specify won't submit more precisely.
EDIT: I do not use dijit/form/Form submit functionality, I just grab form data and send those via XHR to my web service, but I had a look at how submit functionality works and it seems so you need an <iframe> to use submit functionality. So this is what I changed:
A. Form definition - target:"formSubmitIframe" points to iframe id:
<form
id="myForm"
data-dojo-id="myForm"
data-dojo-type="dijit/form/Form"
data-dojo-props="action:'Cart.php', method:'post', target:'formSubmitIframe'"
>
B. Added iframe:
<iframe name="formSubmitIframe" src="about:blank"></iframe>
Once all works for you add style="display:none;" to iframe to hide it.
See it in action in JS Bin: http://jsbin.com/iziwen/7/edit
N.B.: I do not recommend submitting a form this way. If you do not need to go cross-domain or sending files, simply get form data via var data = dijit.byId("myForm").get("value"), so you will have form data in JSON and then send them up via dojo/xhr or dojo/request (for dojo 1.8+).
Also dojo/xhr is capable to send form just by providing a form id to it - here is a nice example: http://livedocs.dojotoolkit.org/dojo/xhr

Categories