Using XMLHttpRequest and post - post

The form works fine with the parameter action= "(path to php file)", but when I try to use the XMLHttpRequest instead I don't get any response.
The reason I want to use XMLHttpRequest is that I want to save the response (text) into an array.
function receivedData(serverReply) {
if (serverReply.readyState == 4 && serverReply.status == 200) {
document.getElementById('main').innerText = serverReply.responseText;
}
else {
console.debug('problem ' + serverReply.errorCode);
}
}
function sendRequest() {
let myForm = new FormData(document.getElementById('timeDateFormId'));
let xhr = new XMLHttpRequest();
xhr.open("POST", "get3.php");
xhr.addEventListener('readystatechange', function () { receivedData(xhr) }, false);
xhr.send(myForm);
}
document.getElementById('timeDateFormId').addEventListener('submit', sendRequest, false)
<form id="timeDateFormId" method="post">
<label>From date (YYYYMMDD)</label>
<input type="text" name="fDate">
<br>
<label>To date (YYYYMMDD)</label>
<input type="text" name="tDate">
<br>
<label>From time (HH:MM)</label>
<input type="text" name="fTime">
<br>
<label>To time (HH:MM)</label>
<input type="text" name="tTime">
<br>
<input type="submit" name="submit" value="go">
</form>

You call the sendRequest method when you submit the form.
Submitting the form causes the browser to navigate to the response from the form submission.
This loads a new page which cancels the Ajax request.
You need to prevent the default behaviour of form submission if you want to run JavaScript instead.
function sendRequest(evt) {
evt.preventDefault();
// etc

Related

_this.testFormEl.nativeElement.submit is not a function for Form Post

I have a hidden form in a dialog which I want to submit automatically.
HTML Code :
<form #formVal method="POST" [action]="urlvalue">
<p *ngFor="let item of redirectData.RedirectData.Form.Parameter;
let pindex = index;">
<input type="hidden" [name]="item.name" [value]="item.value">
</p>
</ form>
`
In my previous angular 1.5 code I was doing
$timeout(() => {
angular.element('#3DSForm').submit();
}, 100);
and it was working but here in Angular 6 I tried using ViewChild in ngAfteronInit but still no luck I am getting error for native element, I even used ngNoform in my HTML but didn't work out.
#ViewChild('formVal') form: ElementRef;
setTimeout(() => {
this.form.nativeElement.submit();
}, 200);
Kindly suggest what am I missing
You probably have some element called submit.
Example:
<input type="hidden" name="submit">
Rename it to something else, e.g btnSubmit.
You should call click event for submit button like this,
<form #formVal method="POST" [action]="urlvalue">
<div *ngFor="let item of redirectData.RedirectData.Form.Parameter; let pindex = index;">
<input type="hidden" [name]="item.name" [value]="item.value">
</div>
<input type="hidden" name="submit" #submitBtn>
</ form>
in ts file
#ViewChild('submitBtn') submitBtn: ElementRef;
submitForm() {
this.submitBtn.nativeElement.click();
}
after that call the submitForm() function from where you want to submit the function.
I was able to achieve it using HTMLFormElement.
<form ngNoForm name="myForm" id="myForm" [action]="urlvalue" method="POST">
<button type="submit" class="test" style="visibility: hidden;"></button>
</form>
This code in the component.
const form: HTMLFormElement = document.getElementById('myForm');
form.submit();

Grails - g:field reset and html reset won't clear form/params/session

Using Grails 3.0.9
Making a Clear Form/session button for the filter class. however nothing i do works.
The button is just stuck there, nothing happens
Any help will be appreciated
SupplyController
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
if (params.name)
session.name = params.name
else if (request.method != "POST")
params.name = session.name
else
session.name = null
def criteria = Supply.createCriteria()
def query = {
and{
if (params.name) {
like ("name", '%' + params.name + '%')
}
}
}
def results = criteria.list(params, query)
respond results, model:[supplyCount: results.getTotalCount()]
}
G:field type of code
<div class="filter">
<h3>Filter:</h3>
<g:form action="index" method="post" >
<label for='name'>Name:</label>
<input type="text" id="name" name="name" value="${session.name}"/><br/>
<span class="button">
<g:submitButton name="index" class="index" value="Apply Filter" /></span>
<g:field type="reset" name="myReset" value="Reset" />
</g:form>
</div>
HTML tag type
<div class="filter">
<h3>Filter:</h3>
<g:form action="index" method="post" >
<label for='name'>Name:</label>
<input type="text" id="name" name="name" value="${session.name}"/><br/>
<span class="button">
<g:submitButton name="index" class="index" value="Apply Filter" /></span>
<input type='reset' value='Reset' />
</g:form>
</div>
An HTML form reset button for a form rests the form to the initial state. In this case back to the values it had when the form loaded. A HTML form reset button does not CLEAR the form or CLEAR the session.
wondering why you are using session for where typicalls form params should be used? In order to clear HTML session you would need to trigger a call back to the originating controller just like you would to post but when it receives via this call. It does a session.invalidate() and then renders same view again. You should try to stick with params for forms. The fact that you have the session information already really no need to post it via a form. Your controller receiving the form would be aware of that same session value.
You could easily create a jquery functionality that you do with a button that triggers and a resetform. jQuery/Javascript function to clear all the fields of a form
Or if that does not work you could try for example in your case:
<g:form ..>
..
<button onClick="clearName();" name="clickme">
</g:form>
<g:javascript>
function clearName() {
$('#name').val();
}
</g:javascript>

How to prevent redirect to new page on form submit

I am trying to upload a form containing multiple files to my server, request is going to correct Action and I am also getting some data but all the files are coming with null values.
var file = function(){
this.submitForm = function () {
$("#addBrtForm").ajaxSubmit(function (response) {
if (response === "Barter Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-afterUpload");
t.somefunction();
} else {
alert("Try Again!! Barter Not Uploaded");
}
});
};
};
hm.files = new file();
//other thing that I tried
$(function(){
$('#addBrtForm').ajaxForm({
type: 'POST',
beforeSubmit: function () {
return false;
},
success: function (response) {
return false;
if (response === "Barter Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-barter");
t.setBarterpageTitle('My Barter');
} else {
alert("Try Again!! Barter Not Uploaded");
}
}
});
});
<form method="post" action="http://localhost:xxxx/Mobile/Home/FileUpload" enctype="multipart/form-data" data-ajax="false" id="addBrtForm" name="addBrtForm" >
<input type="text" name="Title" data-role="none" />
<input type="text" name="Description" data-role="none" />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="Submit" name="" value="submit" data-role="none" multiple />
<input type="Button" name="" value="submit" data-role="none" multiple onclick="hm.files.submitForm()"/>
</form>
It is working perfectly without "ajaxSubmit" but page is redirecting to "http://localhost:xxxx/Mobile/Home/FileUpload", I don't want that page to come up, I just wanted to catch my response and do something based on that
My controller
public ActionResult FileUpload(FormCollection fc, List<HttpPostedFileBase> files)
{
//some functionilty to save data working perfectely
return Json(SuccesMessage, JsonRequestBehavior.AllowGet);
}
*Note - as I am using jquery mobile so there is no views in my project
thanks to accepted answer on this post and Stephen Muecke for suggesting me to look on that question.
what I did-
removed action attribute from my form tag
used on click instead of submit
used ajax to post data as given in the reference link.
My edited js is shown below
var formdata = new FormData($('#addBrtForm').get(0));
$.ajax({
url: "http://localhost:xxxx/Mobile/Home/FileUpload",
type: 'POST',
data: formdata,
processData: false,
contentType: false,
dataType: "json",
success: function (response) {
if (response === "File Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-afterUpload");
t.someFunction();
} else {
alert("Try Again!! File Not Uploaded");
}
},
error: function (e) {
alert("Network error has occurred please try again!");
}
});
changed controller action to this -
public ActionResult FileUpload(UploadModel fm, List<HttpPostedFileBase> files)
{
//some functionilty to save data working perfectely
return Json(SuccesMessage, JsonRequestBehavior.AllowGet);
}
- UploadModel is my model having same Name as I used in my form
Add id to the submit button.
<input type="Button" name="" id="submit" value="submit" data-role="none" multiple/>
Then in the javascript do like this
$(function(){
$('#submit').click(function(e){
Do Your stuf here
e.preventDefault();
});
}

Submitting a form to ASP.NET MVC from Knockout does not bring in all the values

Here is what I have in my view in ASP.NET MVC 5
#model Entities.Coupon
#using (Html.BeginForm("coupon", "marketing", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="scsm-18 scmd-16 sclg-14">
<div class="form-group">
<label>Codes</label>
#Html.TextBoxFor(p => p.Code, new { #class = "form-control", #data_bind = "value: Code", #autofocus = true, #maxlength = "50" })
</div>
<input type="radio" name="IsPerCentOrDollar" value="1" data-bind="checked: IsPerCentOrDollar" />
<span>PercentageAmount</span>
<input type="radio" name="IsPerCentOrDollar" value="2" data-bind="checked: IsPerCentOrDollar" />
<span>DollarAmount</span>
<input type="radio" name="IsPerCentOrDollar" value="3" data-bind="checked: IsPerCentOrDollar" />
<span>FreeShipping</span>
</div>
<div class="panel-footer text-right">
<input type="submit" name="commandType" id="btnSave" class="btn btn-primary" data-bind="click:submit" value="Save" />
</div>
}
In the script:
$(document).ready(function () {
var viewModel = new CouponViewModel(couponModel);
ko.applyBindings(viewModel);
function CouponViewModel(data) {
self.Code = ko.observable(data.Code);
self.IsPerCentOrDollar = ko.observable("1");
self.DiscountLevel = ko.computed(function () {
return self.IsPerCentOrDollar();
});
};
}
Code in MVC:
[HttpPost, ActionName("coupon")]
public ActionResult coupon(Coupon coupon)
{
try
{
// some logic not yet in
}
catch (Exception ex)
{
}
return View();
}
That's all I have in there now.
In Developer tools inside the browser I can see values for self.DiscountLevel change on the selection of radio buttons.
On Submit, at MVC front the value of Code comes in but the values for DiscountLevel are not.
Any help is greatly appreciated.
Regards.
Let me expand on #StephenMuecke's comment (which has the gist of it I think).
ASP.NET MVC's default model binding will fill the argument (Coupon) with values found in the request. Only form elements are sent along with the request. You seem to expect that DiscountLevel is sent along, but it's just a JavaScript function that exists in the user's browser.
Adding something like this may solve your immediate problem:
<input type="hidden" name="DiscountLevel" data-bind="value: DiscountLevel" />
To note a related issue though: the property you have trouble with is a computed observable. However, you probably do not want to send it along as it depends entirely on IsPerCentOrDollar. Just have your server side Coupon class derive the discount level from that property too. That would also prevent users from hacking the hidden input and sending in a malicious value.

Angular JS Multiple Inputs in Form

Would there be any reason that multiple inputs aren't being passed from an Angular form to the controller. Either one of the inputs will submit. The problem is both of them won't submit in the same form.
<form name="myForm" ng-controller="PostIndexCtrl" class="my-form">
<input type='text' ng-model="entry.question_id" name="question_id" value="1">
<input type='text' ng-model="entry.answer" name="answer"><br/>
<button class="btn btn-primary" ng-click="saveEntry()">Save</button>
</form>
Here is the controller
.controller("PostIndexCtrl", function($scope, Post, $resource, $http) {
Post.query(function(data) {
$scope.posts = data;
});
var data = $resource('/api/answers/', {answer: '#answer', question_id: '#question_id'});
$scope.saveEntry = function() {
data.save($scope.entry);
}
});

Resources