Posting data in form html to server using AngularJS Http Post - javascript

I would like to ask about posting problem, actually I have a form below, in that form, I have using ng-submit and ng-click for the function but it didn't work, can anyone help me?
<form method="post" class="sky-form" name="form">
<div class="row">
<div class="col col-12"><img src="public/images/icon_namapasien.png" alt=""/> Nama Pasien</div>
</div>
<div class="row">
<div class="col col-10">
<div ng-repeat="profile in profil">
<label class="input disabled">
<input type="text" ng-model="profile.name">
</label>
</div>
</div>
<div class="col col-2">
<a class="btnstatus"> </a>
</div>
</div><!-- /row -->
<div class="row">
<div class="col col-12"><img src="public/images/icon_tgl.png" alt=""/> Tanggal Lahir</div>
</div>
<div class="row">
<div class="col col-3">
<label class="select">
<div ng-repeat="profile in profil">
<select name="gender" ng-model="profile.birth_date">
<option ng-repeat="n in range(01,31)" value="{{n}}">{{n}}</option>
</select>
<i></i>
</div>
</label>
</div>
<div class="col col-4">
<label class="select">
<div ng-repeat="profile in profil">
<select name="gender" ng-model="profile.birth_month">
<option value="01">Januari</option>
<option value="02">Februari</option>
<option value="03">Maret</option>
<option value="04">April</option>
<option value="05">Mei</option>
<option value="06">Juni</option>
<option value="07">Juli</option>
<option value="08">Agustus</option>
<option value="09">September</option>
<option value="10">Oktober</option>
<option value="11">November</option>
<option value="12">Desember</option>
</select>
<i></i>
</div>
</label>
</div>
<div class="col col-3">
<label class="select">
<div ng-repeat="profile in profil">
<select name="gender" ng-model="profile.birth_year">
<option ng-repeat="n in range(1910,2016)" value="{{n}}">{{n}}</option>
</select>
<i></i>
</div>
</label>
</div>
<div class="col col-2">
<a class="btnstatus"> </a>
</div>
</div><!-- /row -->
<div class="row">
<div class="col col-12"><img src="public/images/icon_gender.png" alt=""/> Jenis Kelamin</div>
</div>
<div class="row">
<div class="col col-10">
<div class="select">
<label class="select">
<div ng-repeat="profile in profil">
<select name="gender" ng-model="profile.gender">
<option value="1">Pria</option>
<option value="0">Wanita</option>
</select>
<i></i>
</div>
</label>
</div>
</div>
<div class="col col-2">
<a class="btnstatus"> </a>
</div>
</div><!-- /row -->
<div class="row">
<div class="col col-12"><img src="public/images/icon_alamat.png" alt=""/> Alamat</div>
</div>
<div class="row">
<div class="col col-10">
<div ng-repeat="profile in profil">
<label class="input disabled">
<input type="text" ng-model="profile.address"/>
<input type="hidden" name="name" value="0" ng-model="kodekota">
</label>
</div>
</div>
<div class="col col-2">
<a class="btnstatus"> </a>
</div>
</div><!-- /row -->
<div class="row">
<div class="col col-12"><img src="public/images/icon_telp.png" alt=""/> Nomor Telepon / Hp</div>
</div>
<div class="row">
<div class="col col-10">
<div ng-repeat="profile in profil">
<label class="input disabled">
<input type="text" value="" ng-model="profile.phone"/>
</label>
</div>
</div>
<div class="col col-2">
<a class="btnstatus"> </a>
</div>
</div><!-- /row -->
<p> </p>
<button class="btn-yellow" type="submit" name="submit" ng-click="postProfil()">Simpan Perubahan</button>
</form>
Here is the angularjs code
$scope.getProfil = function(){
$http.get('/getUrl').success(function(data){
$scope.profil = data;
})
}
$scope.getProfil();
$scope.profile = {};
$scope.postProfil = function(){
$http.post('/postUrl').success(function(data){
$scope.getProfil();
}).error(function(data){
console.log(data);
})
}
$scope.range = function(min, max, step){
step = step || 1;
var input = [];
for (var i = min; i <= max; i += step) input.push(i);
return input;
};
one thing for sure, I know that http.post using only link is a bad idea, but before I do that, I have debug it using alert javascript function, for example I want to get the data from profile.name so I alert it (profile.name) inside the postProfil function but it returns undefined.
here is the key that should be inputed in the http.post
address
phone
birth
gender
name
I would like to use the http array structure such as
$http.post({
method: 'POST',
url: '/postUrl',
data: {
//data is here
}
})
what do you guys think? Thanks
EDIT:
Maybe I will change my questions, do you know the code for updating data from previous data in an apiUrl using AngularJS? So my problem is that getProfil and postProfil is in the same key and value (but I think some of the keys are different).

Just use the ng-model $scope.profile:
$scope.postProfil = function(){
$http.post('/postUrl', $scope.profile).success(function(data){
$scope.getProfil();
}).error(function(data){
console.log(data);
})
}

$http.post('api/create/something', yourData)
should do the trick for your problem.
$http.post accepts (url, data?, options?)
$http on the other hand accepts (options) directly. You can use it like
$http({
url: 'api/create/something',
data: yourData,
method: 'POST'
}).then(....)
This code works the same with the code above.
Regarding the inaccurate data binding. It might be case sensitivity issues, or serialization issues coming from your rest api configuration. Sometimes PascalCased variable does not bind to camelCased variables as it is. Some configurations are needed to be done.

Related

How to Enable or Disable Bootstrap-Select Dropdown with radiobutton using Javascript and jquery

I have two radio buttons and one Bootstrap-select Dropdown.I want to enable/disable dropdown using javascript with the help of two radio buttons.
My Html Code is Given Below:
<div class="container" style="margin-top: 5px;background-color: wheat;">
<div class="card" style="background-color: white;margin: 1em">
<!--<div class="card-header"></div>-->
<div class="card-body">
<div class="row">
<div class="col-lg-2">
<label style="margin-top: 1.2em;margin-left: 1em">Type</label>
</div>
<div class="row" >
<div class="col-sm-1">
<div class="form-check" style="margin-top: 1.1em;margin-left: 1em">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="rbType" id="typeNew" value="enable" >New
</label>
</div>
</div>
<div class="col-sm-2">
<div class="form-check" style="margin-top: 1.1em;margin-left: 1em">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="rbType" id="typeVisisting" value="disable">Visiting
</label>
</div>
</div>
</div>
</div>
<div class="row" >
<div class="col-lg-2">
<label style="margin-top: 1.2em;margin-left: 1em" for="selectCustomer" >Customer Name</label>
</div>
<div class="col-lg-10">
<div class="form-group" style="margin-top: .5em;margin-right: 1em">
<select class=" form-control input-lg" data-live-search="true" title="-- Select a Customer --" name="selectCustomer" id="selectCustomer" >
<!--<option value="none">-- Select a Customer --</option>-->
#foreach($customers as $customer)
<option value="{{$customer->customer_id}}">{{$customer->customer_id}} {{$customer->customer_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
Please help me to solve this problem.I am working at this upto three days.
Add the jquery below
$('input[name="rbType"]').change(function(){
if(this.value == "enable"){
$('#selectCustomer').removeAttr('disabled')
}
if(this.value == "disable"){
$('#selectCustomer').attr('disabled','true')
}
})
Try this in your javascript tag using jquery
$('input[name="rbType"]').change(function(){
if(this.value == "enable"){
$('#selectCustomer').prop('disabled',false)
}
if(this.value == "disable"){
$('#selectCustomer').prop('disabled','true')
}
})

Getting a HTML select value and and input value from submit angular 6

Getting a HTML select value and and input value from form submit ,
in here i get only undefined for the select value, and gives error on
Cannot read property 'target' of undefined
at RightcomponentComponent.push../src/app/rightcomponent/rightcomponent.component.ts.RightcomponentComponent.formSubmit
rightcomponent.component.html
<!--Form start-->
<form >
<div class="row">
<div class="form-group row">
<div style="margin-left: 60px;margin-right:50px ">
<select class="form-control" (ngModelChange)="onSelected($event)" id="sel1">
<option *ngFor="let stock_name of stock_names" [value]="stock_name.stockName">{{stock_name.stockName}}</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="container set_buttons_div" >
<div class="form-group row">
<div class="col-xs-2">
<input class="form-control" id="ex1" type="text">
<br>
</div>
</div>
</div>
</div>
<br>
<div class="row">
<a class="btn btn-sq-lg btn-success b_s_buttons" (click)="formSubmit(e)">
<i class="glyphicon glyphicon-thumbs-up fa-5x"></i><br/>
Buy
</a>
</div>
<br>
</form>
rightcomponent.component.ts
formSubmit(e){
var stock = this.onSelected(e);
console.log(stock);
var quantity = e.target.elements[0].value;
console.log(quantity);
}
onSelected(e){
var stock_company_name = e;
return stock_company_name;
}
I would have created component in this way, i dont know how to create a plunker / fiddler, but two way binding will work for you now. I created this way. :D
<!--Form start-->
<form #myForm="ngForm" novalidate>
<div class="row">
<div class="form-group row">
<div style="margin-left: 60px;margin-right:50px ">
<select class="form-control" (change)="onSelected($event)" id="sel1" name="stock" [(ngModel)]="Model.stockname">
<option *ngFor="let stock_name of stock_names" [value]="stock_name.stockName">{{stock_name.stockName}}</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="container set_buttons_div" >
<div class="form-group row">
<div class="col-xs-2">
<input class="form-control" id="ex1" type="text" name="companyName" [(ngModel)]="Model.companyname">
<br>
</div>
</div>
</div>
</div>
<br>
<div class="row">
<a class="btn btn-sq-lg btn-success b_s_buttons" (click)="formSubmit()">
<i class="glyphicon glyphicon-thumbs-up fa-5x"></i><br/>
Buy
</a>
</div>
<br>
</form>
rightcomponent.component.ts
// create an Object model with form fields as key
Model = {
stockname: '',
companyname: ''
}
formSubmit(){
console.log(this.Model);
}

this.validator is not a function with formarray. Angular2

I'm working on a page which has a nested Formarray.
constructor(private fb: FormBuilder) {
this.buildForm();
}
private buildForm() {
this.trialBudgetForm = this.fb.group({
clients: this.fb.array([])
})
}
addCustomer() {
this.clients.push(this.initCustomer());
}
initCustomer() {
return this.fb.group({
earnedIncomes: this.fb.array([this.initIncome()]),
thirtyAndOneThirdYN: [],
thirtyYN: [],
earnedIncomeExpenseType: [],
earnedIncomeExpense: [],
dependentCareExpense: []
})
}
initIncome() {
return this.fb.group(new ScrAmountType());
}
ngOnInit() {
this.populateData();
}
populateData() {
const clients = this.TrialBudgetData.clients;
const customerFGs = clients.map(customer => this.fb.group({
earnedIncomes: this.populateIncome(customer.earnedIncomes),
thirtyAndOneThirdYN: [this.utilService.YNConvert(customer.thirtyAndOneThirdYN)],
thirtyYN: [this.utilService.YNConvert(customer.thirtyYN)],
earnedIncomeExpenseType: [customer.earnedIncomeExpenseType],
earnedIncomeExpense: [customer.earnedIncomeExpense],
dependentCareExpense: [customer.dependentCareExpense]
}));
const customerFormArray = this.fb.array(customerFGs);
this.trialBudgetForm.setControl('clients', customerFormArray);
}
for demo purpose, i didn't post the entire ts file, coz there are almost 600 lines. But i can provide more detail if needed.
here's the html page (also only a snippet)
<form novalidate [formGroup]="trialBudgetForm" (ngSubmit)="save(trialBudgetForm)">
<div class="settingsPage-box">
<h3 class="box-border-bottom">Earned Income
<span class="float_right add-field add-margin hand" (click)="addCustomer()">
<i class=" fa fa-plus-circle fa-lg plusIconColor"></i>
<span>
Add Earned Income
</span>
</span>
</h3>
<div formArrayName="clients">
<div *ngFor="let earnedIncomeCustomer of clients.controls; let i = index" [formGroupName]="i" class="row-view box-border-bottom">
<div class="box-border-bottom row-view">
<div class="col-sm-3 padding0">
<label for="customer{{i+1}}" class="pushDown">Customer {{i+1}}:</label>
</div>
<div class="col-sm-9 grid-block padding0">
<div class="col-sm-1 float_right" (click)="deleteCustomer(i)">
<span class="delete-row hand">
<i class="fa fa-trash-o"></i>
</span>
</div>
</div>
<div class="col-sm-3">
<label class="pushDown">Earned Income</label>
</div>
<div class="col-sm-9 grid-block">
<div class="row">
<div class="col-sm-6 u-justifyEnd">
<span class="add-margin float-left hand" (click)="addEarnedIncome(i)"><i class=" fa fa-plus-circle fa-lg plusIconColor"></i><span> Add Income</span></span>
</div>
</div>
<div class="row grid-block pd-left amount-grid" formArrayName="earnedIncomes" >
<div class="row-view" *ngFor="let earnedIncome of earnedIncomeCustomer.controls.earnedIncomes.controls; let j = index"
[formGroupName]="j">
<div class="col-sm-5 padding5">
<span class="label-type" *ngIf="j==0">Type</span>
<select class="form-control" formControlName="type" (change)="checkForDuplicateEarnedIncomeType(this.trialBudgetForm.controls.clients.controls[i].controls.earnedIncomes.controls[j].value.type)">
<option value="">Select</option>
<option *ngFor="let optionEntity of this.constantsService.getDropDownFromLookup(this.constantsService.getText('EarningType'))"
value="{{optionEntity.lookupBean.code}}">{{optionEntity.lookupBean.longLabel}}</option>
</select>
</div>
<div class="col-sm-6 pd-left padding5 amount-bg">
<span class="label-type" *ngIf="j==0">Amount</span>
<div class="search-container">
<input (keypress)="this.customValidatorsService.validateNumberOnly($event)" formControlName="amount" class="form-control amount-input search-box"
placeholder="$0.00" currencyMask [options]="{ allowNegative: false,prefix: '$',hundreds: ',' }" maxlength="12"
(keyup)="calculateTotalIncome(earnedIncomeCustomer, i)" />
</div>
<div class="clearfix"></div>
</div>
<div class="col-sm-1 pd-left">
<span class="label-type" *ngIf="j==0"> </span>
<span class="delete-row hand" (click)="deleteIncome(earnedIncomeCustomer, i, j)"> <!-- G.S Income.controls.amount -->
<i class="fa fa-trash-o"></i>
</span>
</div>
</div>
<div class="row-view">
<div class="col-sm-5">
<span class="total-info text-right">Total Earned Income</span>
</div>
<div class="col-sm-6 pd-left amount-bg">
<span class="total-info text-right">${{ earnedIncomeCustomer.totalEarnedIncome | number : '1.2-2'}}
</span>
<div class="clearfix"></div>
</div>
</div>
<div class="row-view">
<div class="col-sm-12 text-center">
<div class="clearfix"></div>
</div>
</div>
</div>
<span *ngIf="duplicateEarnedIncomeType" class="red-font-color">Choose a different use type</span>
</div>
<div class="clearfix"></div>
</div>
<div class="box-border-bottom row-view">
<div class="col-sm-3">
<label class="pushDown">Earned Income Options</label>
</div>
<div class="col-sm-8 grid-block">
<div class="col-sm-5 form-group label-check display-check">
<input type="checkbox" id="check-1" formControlName="thirtyAndOneThirdYN">
<label for="check-1">30+1/3</label>
</div>
<div class="col-sm-6 form-group label-check display-check">
<input type="checkbox" id="check-2" formControlName="thirtyYN">
<label for="check-2">$30</label>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="box-border-bottom row-view">
<div class="col-sm-3">
<label class="pushDown">Earned Income Expenses</label>
</div>
<div class="col-sm-8 grid-block">
<div class="col-sm-5 form-group padding_right">
<div class="control-label">Type</div>
<select class="form-control" formControlName="earnedIncomeExpenseType">
<option value="-1">Select</option>
<option *ngFor="let optionEntity of this.constantsService.getDropDownFromLookup(this.constantsService.getText('EIexpenseType'))"
value="{{optionEntity.lookupBean.code}}">{{optionEntity.lookupBean.longLabel}}</option>
</select>
</div>
<div class="col-sm-6 padding0 padding_custom">
<div class="control-label">Amount</div>
<input formControlName="earnedIncomeExpense" currencyMask (keypress)="numberOnly($event)" class="form-control" [options]="{ allowNegative: false, prefix: '$',hundreds: ',' }"
placeholder="$0.00" maxlength="10" />
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="row-view">
<div class="col-sm-3">
<label class="pushDown">Dependent Care Expenses</label>
</div>
<div class="col-sm-8 grid-block">
<div class="col-sm-5">
<div class="control-label">Expenses</div>
<input (keypress)="numberOnly($event)" currencyMask formControlName="dependentCareExpense" class="form-control" maxlength="10"
placeholder="$0.00" [options]="{ allowNegative: false, prefix: '$',hundreds: ',' }" />
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</form>
I have been trying to debug this for couple days now. The issue happens after constructor executed and before ngOnInit was called. this error only occur when I added more than one customer, and come back to this page. (adding customer won't cause any problem, only when I comeback to this page that's when the error this.validator is not a function is shown.
It's strange because the error happen between constructor and ngOnInit, and populateData is called in ngOnInit, which means error occured before the page know how many customers will I load. But if only the error occur because I add more than one customer, it seems that applicaiton has to get that info within constructor, in which i didn't load the data yet.
Update 1: Sept 25 3:39PM EST
updated with populateData function
Update 2: full stack error: Sept 25 4:09PM EST
TrialBudgetComponent_Host.html:1 ERROR TypeError: this.validator is not a function
at FormControl.webpackJsonp.../../../forms/#angular/forms.es5.js.AbstractControl._runValidator (forms.es5.js:2645)
at FormControl.webpackJsonp.../../../forms/#angular/forms.es5.js.AbstractControl.updateValueAndValidity (forms.es5.js:2613)
at new FormControl (forms.es5.js:2936)
at FormBuilder.webpackJsonp.../../../forms/#angular/forms.es5.js.FormBuilder.control (forms.es5.js:5780)
at FormBuilder.webpackJsonp.../../../forms/#angular/forms.es5.js.FormBuilder._createControl (forms.es5.js:5822)
at forms.es5.js:5804
at Array.forEach (<anonymous>)
at FormBuilder.webpackJsonp.../../../forms/#angular/forms.es5.js.FormBuilder._reduceControls (forms.es5.js:5803)
at FormBuilder.webpackJsonp.../../../forms/#angular/forms.es5.js.FormBuilder.group (forms.es5.js:5762)
at TrialBudgetComponent.webpackJsonp.../../../../../src/app/trial-budget/trial-budget.component.ts.TrialBudgetComponent.toFromGroup (trial-budget.component.ts:102)
Update 3 question closed: thanks to #yurzui's comment
I just realized that the architecture is messed up for this page. This component has a parent which only has (current component selector) in its template. The two component has exactly the same name just under different folder. The parent is at /trial-budget and children is at /trial-budget/trial-budget-main. The TrialBudgetComponent.toFromGroup is actually a function inside the parent. For some reason, it's being called inside ngInit instead of constructor. Still haven't figure out why error only happen with 2 customer.
But lesson learned:
1. read error message carefully especially first and last couple lines. I didn't read the last line.
2. always construct form inside constructor and populate data inside ngOnInit()

ng-if is not working with select ngmodel value

Iam working on ionic project.Here Iam trying to display some data on selection of options.I have written code in the way that when user selects all the 3 select options,then a form has to be appeared with some data.I have taken the ngmodel for 3 select options and after choosing 3rd select option,form should be appear,for that I used the 3rd select option ng-model in the ng-if for the div tag.But it's not working.Below is my code:
<div class="row form-group" ng-controller="myProfileCtrl">
<div class="col-md-3 col-sm-4 col-xs-6 margin1">
<select class="form-control" ng-change="loadtypes()" ng-model="selectedIndustry" ng-options="industry for industry in name">
<option value="">Select Industry</option>
</select>
</div>
<div class="col-md-3 col-sm-4 col-xs-6 margin1">
<select class="form-control" ng-change="loadProducts()" ng-model="selectedtype" ng-options="make_year.make_year for make_year in makeYear">
<option value="">Select Type</option>
</select>
</div>
<div class="col-md-3 col-sm-4 col-xs-6 margin1">
<select class="form-control" ng-change="loadServices()" ng-model="selectedProduct" ng-options="car_model.car_model for car_model in carModel">
<option value="">Select Product</option>
</select>
</div>
</div>
<!--Table or div-->
<div ng-if="selectedProduct">
<form class="form-group">
<div class="row">
<div class="col col-33">
<b>Service Issue</b>
</div>
<div class="col col-33">
<b> Tick</b>
</div>
<div class="col col-33">
<b> Cost</b>
</div>
</div>
<div class="row" ng-repeat="services in serviceData" style="margin-bottom:5px;">
<div class="col col-33">
<label>{{services.services}}</label>
</div>
<div class="col col-33">
<input type="checkbox" value="" ng-model="checks[$index]" />
</div>
<div class="col col-33">
<input class="form-control" type="text" style="width:100px;" ng-model="inputs[$index]" />
</div>
</div>
<div class="row">
<div class="col col-50">
<b>Service Request</b>
</div>
<div class="col col-50">
<b> Tick</b>
</div>
</div>
<div class="row">
<div class="col col-50">
<label>First Response</label>
</div>
<div class="col col-50">
<input type="checkbox" ng-model="ser.firstResponse" />
</div>
</div>
<div class="row">
<div class="col col-50">
<b>Location</b>
</div>
<div class="col col-50">
<input class="form-control" list="places" name="location" ng-model="ser.location" />
<datalist id="places">
<option value="Kochi-Kerala">
<option value="Pune-Maharastra">
<option value="Bangalore-Karnataka">
<option value="Hyderabad-Telangana">
</datalist>
</div>
</div>
<div class="row">
<div class="col col-50">
<b>Resolution Time</b>
</div>
<div class="col col-50">
<input type="number" class="form-control" min="1" ng-model="ser.resolution" />
</div>
</div>
<div class="row">
<div class="col col-50">
<b>Prioritized preferred partners</b>
</div>
<div class="col col-50">
<input type="checkbox" ng-model="ser.partners" />
</div>
</div>
</form>
<button type="button" class="btn btn-primary" ng-click="add()">Save</button>
</div>
How can I display the data in the form after selection of options in angularjs?
would you write the value of carModel , because I test your code with my value and its OK, look at html:
<select class="form-control" ng-change="loadServices()" ng-model="selectedProduct" ng-options="item.label for item in items">
<option value="">Select Product</option>
</select>
<div ng-if="selectedProduct">
mozhdeh
</div>
and controller :
$scope.items = [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}];

POSTING form contents using AJAX/JSON/JAVASCRIPT to a PHP script

I've been looking around for an explanation on how to do this for a while but haven't found a decent explanation yet, so apologies if this is a repeat.
I don't have any problem retrieving JSON using GET but I'm confused as to how to use POST to send JSON and have it interpreted at the far end by a PHP script
I'm trying to do this on localhost for now.
Form is as follows:
<div class="row">
<div class="col-sm-2 spacer"> </div>
<div class="col-sm-8 topSpaceNeeded"><h4>Select Currencies to Exchange</h4></div>
<div class="col-sm-2 spacer"> </div>
</div>
<div class="row">
<div class="col-sm-1"> </div>
<div class="col-sm-10">
<form id="formSendDataWithAjax" method="POST" action="./postedJsonData">
<div id="formSection1">
<div class="row">
<div class="col-sm-12"> </div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="userId">User ID</label>
<select class="form-control" id="userId" name="userId">
<option value="123456">123456</option>
<option value="654321">654321</option>
<option value="134256">134256</option>
<option value="652431">652431</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="originatingCountry" id="countryLabel">Country of Origin</label>
<select class="form-control" id="originatingCountry" name="originatingCountry">
<option value="IE">IRELAND</option>
<option value="EN">ENGLAND</option>
<option value="FR">FRANCE</option>
<option value="PL">POLAND</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="currencyFrom">Base Currency</label>
<select class="form-control" id="currencyFrom" name="currencyFrom" >
<option value="AUD">AUD</OPTION>
<option value="CAD">CAD</OPTION>
<option value="CHF">CHF</OPTION>
<option value="CZK">CZK</OPTION>
<option value="DKK">DKK</OPTION>
<option value="EUR" SELECTED>EUR</OPTION>
<option value="GBP">GBP</OPTION>
<option value="HKD">HKD</OPTION>
<option value="HUF">HUF</OPTION>
<option value="NOK">NOK</OPTION>
<option value="NZD">NZD</OPTION>
<option value="PLN">PLN</OPTION>
<option value="SEK">SEK</OPTION>
<option value="USD">USD</OPTION>
<option value="ZAR">ZAR</OPTION>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="currencyTo">Buy Currency</label>
<select class="form-control" id="currencyTo" name="currencyTo">
<option value="AUD">AUD</OPTION>
<option value="CAD">CAD</OPTION>
<option value="CHF">CHF</OPTION>
<option value="DKK">DKK</OPTION>
<option value="EUR" SELECTED>EUR</OPTION>
<option value="GBP">GBP</OPTION>
<option value="HKD">HKD</OPTION>
<option value="HUF">HUF</OPTION>
<option value="NOK">NOK</OPTION>
<option value="NZD">NZD</OPTION>
<option value="PLN">PLN</OPTION>
<option value="SEK">SEK</OPTION>
<option value="USD">USD</OPTION>
<option value="ZAR">ZAR</OPTION>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12"> </div>
</div>
</div>
<div id="formSection2">
<div class="row">
<div class="col-sm-12"> </div>
</div>
<div class="row">
<div class="col-sm-4"> </div>
<div class="col-sm-4">
<div class="form-group">
<label for="rate" id="rateLabel"> </label>
<input type="hidden" id="rate" name="rate" value="" >
</div>
</div>
<div class="col-sm-4"> </div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="amountSell">You Sell:</label>
<input type="number" class="form-control" step="0.10" id="amountSell" name="amountSell" value="1.00" >
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="amountBuy">You Buy:</label>
<input type="number" class="form-control" step="0.01" id="amountBuy" name="amountBuy" value="1.00" >
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12"> </div>
</div>
<div class="row">
<div class="col-sm-4"> </div>
<div class="col-sm-4">
<input type="submit" id="transfer" class="btn btn-primary btn-block" id="transfer" name="transfer" value="TRANSFER NOW">
</div>
<div class="col-sm-4"> </div>
</div>
</div>
</form>
</div>
<div class="col-sm-1"> </div>
</div>
I know it's probably easier to use JQuery, but Javascript is what I know so I'd like to stick with that if possible.
The Javascript is as follows:
document.getElementById('formSendDataWithAjax').onsubmit =submitDataWithAjax;
function submitDataWithAjax(e)
{
// intercept form submission by preventing the script from following the url of the form
e.preventDefault();
var f = e.target,
formData= new FormData(f),
xhr = new XMLHttpRequest();
xhr.open("POST", f.action);
xhr.setRequestHeader("Content-Type","application/json; charset=utf-8");
xhr.send(formData);
}
What I believe this script should do is prevent the postedJsonData page from loading when the form is submitted. Instead, the data is converted to JSON and should then be sent via AJAX to the postedJsonData PHP script
If this is correct, how do I get postedJsonData script to listen for the data?
Is it enough to do this to extract it to an array?
$dataArr = file_get_contents("php://input");
jQuery is much easier, I'd highly recommend it.
To use jQuery, just include this at the top of your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Then, to do AJAX/JSON/PHP requests, replace what you currently have in your Javascript file with:
$(document).ready(function() {
$("#formSendDataWithAjax").submit(function() { //Whenever form with ID="formSendDataWithAjax" is submitted
$.ajax({ //Make AJAX POST call
type: "POST", //POST, instead of GET
url: "postedJsonData.php", //Location of PHP script
dataType: "JSON", //JSON
data: {
userid: $("#userId").val(), //These values will be JSON-encoded automatically
country: $("#originatingCountry").val(), //Magically JSON-encoded
etc.
}
}).done(function(returnValue) { //returnValue could be any JSON string: "{ "result" : "success" }, { "result" : "error" }, etc.
alert("Your PHP script returned this value: "+returnValue);
});
}
return false;
}
Then in your PHP script, simply calling $_POST['userid'] or $_POST['country'] will give you the value POSTed by the AJAX call. E.g.
<?php
$userid = (int) $_POST['userid'];
$country = $_POST['country'];
//Do stuff
?>

Categories

Resources