Angularjs form submit, url as action iframe as target - html

I am trying to do a form submit which has url as the action and target as iframe. I am getting the action url via an API call. If I hard coded the url in the controller it will work fine. But if i get the url from an API, click on the submit button will do nothing. What could be the problem here. Code is like following code snippets.
HTML
<form action='{{trustedUrl}}' method="POST" target='iframe'>
<input type="text" />
<input type="submit", value="submit" />
</form>
Java Script
var testCtrl = ['$scope',function($scope){
var pageInitialize = function(){
$scope.trustedUrl = '';
getUrl(function(data){
trustedUrl = data.URL;
});
}
}]

You missed out $scope here
getUrl(function(data){
$scope.trustedUrl = data.URL;
//-----^
});

You are missing $sce as follows:
var testCtrl = ['$scope','$sce',function($scope,$sce){
var pageInitialize = function(){
$scope.trustedUrl = '';
getUrl(function(data){
trustedUrl = $sce.trustAsResourceUrl(data.URL);
});
}
}]
You can read more about $sce in the angular documentation.

This works for me in Angular 2
<form target="frame" action="<Your URL to POST>" #form method="POST" hidden="hidden">
<input name="token" value={{token}}>
</form>
And call nativeElement.submit() from nginint() in your component.
similar here
Angular way to submit form data to iframe

Related

Form Input to Change URL

I am in need of an HTML form in which the input would add onto a URL as I have a preexisting API.
Basically, I need an HTML form which would fill in a variable within a URL.
Say I had an API with the URL "https://example.com/api/api?item=<FILL THIS IN WITH THE INPUT>&auth=AUTHENTICATIONtoken", I need to have the input of the HTML form replace "<FILL THIS IN WITH THE INPUT>".
I recall finding a way to do this before-but I can't seem to find it anymore.
You can do this with JavaScript.
If this is your form:
<form onsubmit="changeFormAction()">
<input type="text" id="item">
<button type="submit" id="submitButton">Submit</button>
</form>
and if you have this in your JavaScript:
function changeFormAction() {
var item = document.getElementById("item").value;
var form = this;
form.action = "https://example.com/api/api?item=" + item + "&auth=AUTHENTICATIONtoken";
form.submit();
}
Then the function will automatically change the form action by adding the item specified by the form input.
Demo:
function changeFormAction(event) {
var item = document.getElementById("item").value;
var form = this;
form.action = "https://example.com/api/api?item=" + item + "&auth=AUTHENTICATIONtoken";
// for demonstration, don't actually submit the form, just print out the form action
console.log(form.action);
event.preventDefault();
}
<form onsubmit="changeFormAction(event)">
<input type="text" id="item">
<button type="submit" id="submitButton">Submit</button>
</form>

How to create a submit button with ui-sref in angular

I have a multi-step form, each step having a btn-link to move to the next step. I achieve this with angular routes in this way:
<button ui-sref="next.step" class="btn btn-link"></button>
In one of the steps in the middle of the whole form I need to submit the data, so I need the already described button to submit the form as well and only if the form could be submitted then move to the next step.
I tried doing this but it is not working because it redirects to the next step without taking care about the form
<button ui-sref="next.step2" type="submit" class="btn btn-link"></button>
How can I achieve this using angular?
you don't need to use ui-sref for your next button instead use $state service from your controller as shown below
HTML Code
<form ng-submit="onFormSubmission($event)">
<button type="submit" class="btn btn-link"></button>
</form>
Controller
var successCallback = function(response) {
//process response
$state.go("next.step2");
}
$scope.onFormSubmission = function($event) {
var data = getFormData();
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
}
Use ng-submit to submit the form and show some loading message as form is getting saved, use $http to post the data and on-success take user to next route using $state.go.
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', '$state', function($scope, $state) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
$http.get('/aveData', config).then(function(response){
$state.go('next.step2')
}, function(){
alert('error saving data');
});
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>

Prevent HTML form action from being displayed on browser, or redirect to another page after the action being executed

Alright let's put it this way: How can I "redirect" a user to another page, "MyPage.php" after submitting a form that looks like this:
<form action="http://www.example.com/APageICanNotEdit.php" method="POST">
<input type="submit" name="send" value="Go" />
</form>
Please note that, I don't have control over the URL provided in the action attribute. It's an external source. Which means, I cannot edit the "APageICanNotEdit.php" file.
Here is what I want:
User will click on submit button (Labeled as Go)
action="http://www.example.com/APageICanNotEdit.php" - this action
must be performed, if possible, without displaying the contents of it.
I want the user to reach "MyPage.php" safely after
"APageICanNotEdit.php" is executed.
I need a solution without changing the URL in action, cause that
defeats the purpose.
use an hidden parameter like
<input type="hidden" name="action" value="1" />
Your form will look like this:
<form action="http://www.example.com/form-manager.php" method="POST">
</form>
Yout form manager will look like this:
if ($_POST['action'] == "1")
require_once('ThePHPFileIDoNotWantToBeLoadedOnBrowser.php");
Seeing your comment, you can do it with an AJAX call:
$(document).on('submit' , 'form[action="http://www.example.com/ThePHPFileIDoNotWantToBeLoadedOnBrowser.php"]' , function(e){
var formData = $(this).serialize(); // if you need any of the vars
$.ajax({
url:'someOtherURL.php',
type:'POST',
datatype:'json',
data: formData,
success : function(data){
for(var i = 0; i < data.length; i++){
console.log(data);
}
},
error : function(s , i , error){
console.log(error);
}
});
return true; // keep normal behavior
});

How to send form field value to a REST service using JSON or AJAX

I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!
The HTML:
<form>
<input type="hidden" name="gid" value="12345678">
<input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global">
<input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True">
<input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)">
<input type="submit" name="signup" value="signup" class="email_submit_button">
</form>
Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:
$(".email_submit_button").click(function(){
var uemail = $('.email_input_field').val();
window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True";
return false;
}
});
I see you'r using jQuery so you can use the $.post to post to the server like this:
var url = "http://example.com/automated/action.jsp"
var data ={
"gid": form.gid,
"action": register,
"uemail": form.uemail,
"errorPage": "/automated/action.jsp",
"user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn,
"user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp
};
var success_func = function(data){
//do what you want with the returned data
};
$.post(url, data, success_func);
Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.
EDIT:
I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.
$(".email_submit_button").submit(function(e) {
// stop form from submitting
e.preventDefault();
// Grab all values
var uemail = $('.email_input_field').val();
// make a POST ajax call
$.ajax({
type: "POST",
url: "YOUR URL", // set your URL here
data: {
uemail: uemail // send along this data (can add more data separated by comma)
},
beforeSend: function ( xhr ) {
// maybe tell the user that the request is being processed
$("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>");
}
}).done(function( response ) {
// do something with the received data/response
//$("#status").html(response);
});
});
Not sure if ".email_submit_button" is the class given to the submit button or the form.. you need to use the id or class given to the form and not the submit button.. hope this helps

How can I assign different actions for different submit buttons in same html form?

I am trying to assign different actions to same html form according to different submit buttons.
Can I do something like this ?
<FORM>
------
<INPUT type="submit" value="DoSomething" action="DoSomething.pl" method="POST">
<INPUT type="submit" value="DoSomethingElse" action="DoSomethingElse.pl" method="POST">
<FORM/>
Just in case someone else finds this post:
If you're using HTML5, this is now easier thanks to the formaction attribute. This attribute applies to input and button elements of type="submit" and forces the form to submit to the location specified in the formaction attribute of the clicked element.
Then only drawback of this attribute is that it's not supported by Internet Explorer 9 and lower, but this limitation can be easily overcome using a little JavaScript.
Example:
<form method="post" action="go_default">
<input type="submit" value="Go Left" formaction="go_left" />
<input type="submit" value="Go Right" formaction="go_right" />
</form>
For IE 9 and lower:
<script type="text/javascript">
$(function () {
var $submit = $('form [type="submit"][formaction]');
$submit.click(function() {
var $this = $(this),
action = $this.prop('formaction'),
$form = $this.closest('form');
$form.prop('action', action).submit();
});
});
</script>
No. A form has only one action (action being a property of the form, not the submit button).
The target of the action can do different things on the basis of the values in the form. So, you might want to start naming your submit buttons.
Learn HTML before you even think about writing and deploying a CGI script.
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="action" value="DoSomething">
<input type="submit" name="action" value="DoSomethingElse">
</form>
Note also that choosing an action based on the value of the submit button is a losing strategy if you wish to internationalize the application because the value of a submit button is what the UA displays to humans.
Therefore, script should decide what to do on the basis of some other input element's value.
For example, CGI::Application looks at a run_mode parameter.
Alternatively, you can use different names for your submit buttons as Alec suggests. In that case, you need to check which submit button was pressed by going through the names of the parameters passed to your script which, IMHO, makes the dispatch slightly more cumbersome. It also means it is possible for someone to pass values for all submit buttons to your script (not via the user interface, but via curl or wget or similar programs.
For example, given the HTML
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="submit_left" value="Go Left">
<input type="submit" name="submit_right" value="Go Right">
</form>
here is how your script may handle form submission:
#!/usr/bin/perl
use strict; use warnings;
use CGI::Simple;
my $cgi = CGI::Simple->new;
my %dispatch = (
left => \&handle_left,
right => \&handle_right,
);
my #actions = grep s/^action_(right|left)\z/$1/, $cgi->param;
my $handler = \&handle_invalid_action;
if ( #actions == 1) {
my ($action) = #actions;
if ( exists $dispatch{ $action } ) {
$handler = $dispatch{ $action };
}
}
else {
$handler = \&handle_too_many_actions;
}
$handler->($cgi);
sub handle_left { }
sub handle_right { }
sub handle_invalid_action { }
# because it may indicate someone trying to abuse your script
sub handle_too_many_actions { }
You can also use Ajax for this, and every button has assigned an ajax function that calls it's own php script and you don't even need to refresh the page or redirect, like in this example that i have tried:
HTML:
<input type="submit" value="Make other thing" onclick="ajax_post1();"/>
<input type="submit" value="Make something" onclick="ajax_post2();"/>
<div id="script1Response"></div>
<div id="script2Response"></div>
Javascript functions:
//the first function
function ajax_post1(){
var hr = new XMLHttpRequest();
//take the values from the html input elements you want to use
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
//the script that will process the data
var url="php_script1.php";
//the variable that will contain the information for the php script
var dataVar="var1="+v1+"&var2="+v2;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script1Response").innerHTML = script_response;
}
}
// Send the data to php_script1.php
hr.send(dataVar); // Actually execute the request
document.getElementById("script1Response").innerHTML = "processing...";
}
//the second function
function ajax_post2(){
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
var url="php_script2.php";
var dataVar="var1="+v1+"&var2="+v2;
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script2Response").innerHTML = script_response;
}
}
hr.send(dataVar);
document.getElementById("script2Response").innerHTML = "processing...";
}
The php files will have to contain some variables that will store the values sent by dataVar parameter like this:
$var1_=$_POST['var1']; //the var1 from the dataVar parameter
$var2_=$_POST['var2']; //the var2 from the dataVar parameter
The example I used can be found here:
https://www.youtube.com/watch?v=woNQ2MA_0XU.