HTML Form Doesn't Send Data through AJAX Post - javascript

I have a DataTable that uses AJAX to pull from 8 different SharePoint lists, and organizes them based on there Program attribute, then child row is organized by the Deliverable attribute, followed by the grandchild rows which is the remaining information about the "Deliverable". Everything about that aspect works perfectly for my DataTable.
However, I need to be able to write back information to this DataTable, so the easiest route I thought to take would to be a HTML form read the input, then post it to the corresponding SharePoint list based on its "Program" attribute. I have the form built under the DataTable and I cannot figure out how to get it to send to the SharePoint list. I am currently only using only one Program just to see if it works and I am unsuccessful. I tried to console.log() a few things and nothing showed up.
Here is a picture of my table and form.
Here is my code:
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
'headers': { 'Accept': 'application/json;odata=nometadata' },
success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
data = data;
var table = $('#myTable').DataTable();
table.rows.add( data.value ).draw();
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"pageLength": 100,
"columns": [
{ "data": null, "defaultContent": "" },
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export or Update Table',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
{
text: 'Update Table',
action: function (e, dt, node, config){
$('#myModal').modal('show');
}
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
} );
$(document).ready(function() {
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
// console.log(formData);
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
swal("Item created successfully", "success"); // Used sweet alert for success message
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
h1{
text-align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.modal-dialog-centered {
display:-webkit-box;
display:-ms-flexbox;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
min-height:calc(100% - (.5rem * 2));
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="heading">
<h1 class="center"><strong>Deliverables</strong></h1>
</div>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th></th>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update DataTable</h4>
</div>
<div class="modal-body">
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id = "dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "Yes">Yes</option>
<option value = "No">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn-submit" name="btn-submit" class="btn-submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

var baseUrl = "http://WebAppURL"
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
'headers': { 'Accept': 'application/json;odata=nometadata' },
success: function (data) {
console.log(data);
if(data.d != null && data.d != undefined && data.d.results.length> 0){
var table = $('#myTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"pageLength": 100,
"columns": [
{ "data": null, "defaultContent": "" },
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export or Update Table',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
{
text: 'Update Table',
action: function (e, dt, node, config){
$('#myModal').modal('show');
}
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
alert("Item created successfully", "success");
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
h1{
text-align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.modal-dialog-centered {
display:-webkit-box;
display:-ms-flexbox;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
min-height:calc(100% - (.5rem * 2));
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="heading">
<h1 class="center"><strong>Deliverables</strong></h1>
</div>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th></th>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update DataTable</h4>
</div>
<div class="modal-body">
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id = "dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "Yes">Yes</option>
<option value = "No">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn-submit" name="btn-submit" class="btn-submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Your Snippit contains error/warnings as following:
URL array binding which is string break on array child.
Undefined object used to bind, SharePoint Rest API data parameter in
Success method data.value is used while REST API returns JSON results as data.d.results.
Multiple document ready
baseUrl variable is not defined
Rest of all is good now but needs more code optimization.
Set baseUrl = "http://webappurl"; with your server/webappurl and try this snippit.
Try this snippit, Hope this can help you now.

So i made Test in my environment SP-OnPrem 2013 and using a Script Editor webpart.
Here is the result. I made two list with Deliverables and saved this in Test1Deliverable.
Oh Gosh, I thought it was oblivious that you can bind variables from input field values to insert them in SP list but you are assigning them as the name of the field in input html. so you need to replace this section of script
'Program': program,
'Deliverable': deliverable,
'To': to,
'Date': date,
'Approved': approved,
'Notes': notes
Replace with
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
Note: I gave Id to all the input and select elements and using their value to POST them into SP. After submit , just refresh the page or call loadData() again and in my case Notes1 and Date1 columns used.
In Case of My Script Editor Code:
<style type="text/css">
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
</style>
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</tfoot>
</table>
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id="dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "True">Yes</option>
<option value = "False">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn" name="btn" class="btn" value="Submit" />
</div>
</fieldset>
</form>
<script type="text/javascript">
var baseUrl = "http://webappurl";
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
console.log(data);
if(data.d != null && data.d != undefined && data.d.results.length> 0){
var table = $('#myTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"columns": [
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
});
$(document).ready(function() {
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
// console.log(formData);
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
alert("Item created successfully", "success"); // Used sweet alert for success message
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
</script>
</div>

You do not need to much of script, best way to submit form by onsubmit method using return false. You can use Jquery post method for this.

Related

Html Table header won't appear on max width

I have a table using jquery datatable plugin and for some reason the header appears like this, if i click sort or some other action the header automatically resizes to max-width.
here is the code
<div class="card-body">
<div class="container-fluid">
<div id="content" class="d-none">
<div class="table-responsive">
<table id="tblParametros" class="table custom-table text-center">
<thead>
<tr>
<th>Id</th>
<th>Referência</th>
<th>UAP</th>
<th>Nº de Dias</th>
<th>Nº de Turnos</th>
<th>Nº de PAB(s)</th>
<th>Alcance de Abastecimento</th>
<th>Quantidade Mínima</th>
<th>Quantidade Máxima</th>
<th></th>
</tr>
</thead>
</table>
</div>
<!-- Modal structure -->
<div id="modal" class="iziModal custom-modal" data-iziModal-fullscreen="true" data-iziModal-title="Parâmetro" data-iziModal-subtitle="Edição de parâmetros" data-iziModal-icon="fas fa-edit">
<section>
<!-- Modal content from partial view -->
<div class="container-fluid p-5 iziModal-content">
<partial name="_EditPartial" for="Parametro" />
</div>
</section>
</div>
</div>
<div id="loading" class="text-center">
<img src="~/images/ajax/loader-ellipsis.svg" />
</div>
</div>
</div>
js
$(document).ajaxStart(function () {
$("#loading").show();
$("#content").addClass('d-none');
}).ajaxStop(function () {
$("#loading").hide();
$("#content").removeClass('d-none');
});
$(function () {
var table = $('#tblParametros').DataTable({
scrollY: "60vh",
ajax: {
url: '#Url.Action("List","Parametros")',
dataSrc: ""
},
columns: [
{ data: "id" },
{ data: "referencia" },
{ data: "uap" },
{ data: "numDias" },
{ data: "numTurnos" },
{ data: "numPAB" },
{ data: "alcanceAbastecimento" },
{ data: "qtdMin" },
{ data: "qtdMax" },
{
data: "id",
render: function (data, type, row) {
return '<button class="btn" onclick="EditParametro('+data+')" data-izimodal-open="#modal" data-izimodal-transitionin="fadeInDown">' +
'<i class="fas fa-edit"></i>' +
'</button>';
}
}
]
});
});
and some custom styles i apply
.custom-table {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
width:100%;
}
.custom-table > thead {
background-color: #3e5977;
color: white;
}
.custom-table > tbody {
background-color: #97c7fb;
color: white;
font-weight: bold;
}
.custom-table > tbody > tr > td > button {
background-color: #3e5977;
border-color: #ddd;
}
.custom-table > tbody > tr > td > button:hover {
background-color: #7191b4;
border-color: #ddd;
}
.custom-table > tbody > tr > td > button > svg {
color: #fdba9f;
}
.custom-table > tbody > tr:nth-child(even) {
background-color: #43515f75;
}
.custom-table > tbody > tr:nth-child(odd) {
background-color: #2c3b4b8f;
}
I don't understand why does it do this, i thought it was 'cause of the class "table-responsive" but wasn't the guilty one

Cannot Get / nodeJS problem, why do I get this message?

Please help - I am getting Cannot Get / in my NodeJS application. Why do I get this message?
I know it was here, sorry, but I can't figure out why I get the message.
I tried everything that I could and I still don't get it.
.............
.............
.............
.............
.............
index.js
var express=require('express');
var filePersonData = require("fs")
var jsonData=require('./persons.json');
var parser = require("body-parser");
var jsonFile = "./persons.json"
var app=express();
app.use(parser.urlencoded({extended:true}));
app.use(parser.json());
app.use(express.static("./web"));
// WRITE TO FILE
function readPerson(){
var file = filePersonData.readFileSync(jsonFile, "utf-8");
var jsonDATA = JSON.parse(file);
return jsonDATA;
}
// WRITE NEW PERSON TO FILE
function addPerson(person){
var jsonDATA = readPerson();
jsonDATA.persons.push(person);
filePersonData.writeFileSync(jsonFile, JSON.stringify(jsonDATA));
}
// CHECK IF PERSON EXIST
function ifExist(newPerson){
var jsonDATA = readPerson();
for(var person of jsonDATA.persons){
if(person.name.toLowerCase() == newPerson.name.toLowerCase())
return true;
}
return false;
}
// post to web
app.post("/api/newPerson", function(request, response) {
var person =request.body;
if(ifExist(person)){
response.status(400);
}else{
response.status(201);
addPerson(person);
}
response.send();
});
app.get('/api/persons',(req,res)=>{
res.status(200);
var jsonDATA = readPerson();
res.send(JSON.stringify(jsonDATA));
});
// listening to port 3500
app.listen(3500,
()=>{console.log("Server is listening to port 3500")});
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
<script>
function loadData() {
let optionList = document.getElementById('country').options;
let options = ["Afghanistan", "Åland Islands", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua
and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria",
"Azerbaijan", "Bahamas", "Bahrain"];
options.forEach(option =>
optionList.add(new Option(option, option)));
}
//Get the person info
function newPerson() {
var person = {
name: document.getElementById("name").value,
age: Number(document.getElementById("age").value),
isMale: Boolean(document.getElementById("isMale").checked),
country: document.getElementById("country").value
};
//Check validation
if (!validateParameters(person)) {
return;
}
//fetch : get the web
fetch(`/api/newPerson`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(person),
})
.then(res => {
if (res.status == 201) {
alert(person.name + " added successfully");
window.location = "/personsData.html";
} else if (res.status == 400) {
alert("ERROR: Name already exist");
}
})
.catch(err => console.log(`ERROR : ${err}`));
}
/*
* Validation : person input
* Check if person name between 3-15
* Check if person age betwen 0-120
*/
function validateParameters(person) {
if (person.name.length < 3 || person.name.length > 15) {
alert("The name : " + person.name + " must contain more that 3
latters and below 15 ");
return false;
}
if (person.age < 0 || person.age > 120 || person.age == "") {
alert("The age " + person.age + " is wrong neew to be between 1-
120");
return false;
}
return true;
}
</script>
</head>
<body onload="loadData()">
<div class="center">
<label style="font-size:30px;">Name:</label>
<input style="font-size:20px;" type="text" id="name" placeholder="Your
name..." />
</div>
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Age:</label>
<input style="font-size:20px;" type="number" id="age" placeholder="Your
age..." />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Is Male ? </label>
<input style="font-size:20px;" type="checkbox" id="isMale" />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Country:</label>
<select style="font-size:20px;" id="country" placeholder="Your
country...">
</div>
<div class="center">
</select>
<br/>
<br/>
<input onclick="newPerson()" type="submit" value="ADD"></input>
</div>
</body>
</html>
personsData.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 1500px;
width: 80%;
background-color: powderblue;
}
b.filds {
font-size: 30px;
color: rgb(99, 31, 189);
padding-right: 10px;
padding-left: 10px;
}
body {
color: rebeccapurple;
}
h1 {
text-decoration: underline;
}
</style>
<script>
//Add all persons to personView string and print the data to html page
function formatPersons(personList) {
var personView = "";
for (person of personList) {
personView += `<b class="filds">| Name:</b>
<b class="filds">${person.name}</b>,</b>
<b class="filds">| Age: </b>
<b class="filds"><b class="filds">${person.age}</b>,</b>
<b class="filds">| is Male: </b>
<b class="filds"><b class="filds">${person.isMale}</b>,</b>
<b class="filds">| Country: </b>
<b class="filds"><b class="filds">${person.country}</b>.</b>
<br\>`;
}
document.getElementById("body").innerHTML = personView;
}
//Load data from persons JSON
function getAllPersons() {
fetch(`/api/persons`)
.then(res => res.json())
.then(body => formatPersons(body.persons))
.catch(err => console.log(`Error: ${err}`));
}
</script>
</style>
</head>
<body onload="getAllPersons()">
<h1>Persons data</h1>
<div>
<p id="body"></p>
</div>
</body>
</html>
When you hit the express server, it searches for index.html for path "/" by default. In your case, you don't have both defined. you should be able to access both of your pages with localhost:port/form.html" and localhost:port/personsData.html.

Why i am not able to submit the form?

i am working on payment gateway, in that when i try to submit form with jquery it doesn't submit the form $('#checkout_form').submit(); here is my whole code for that
braintree.client.create({
authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b'
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationMonth: {
selector: '#expiration-month',
placeholder: 'MM'
},
expirationYear: {
selector: '#expiration-year',
placeholder: 'YY'
},
postalCode: {
selector: '#postal-code',
placeholder: '90210'
}
}
}, function (err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
if (field.isValid) {
if (event.emittedBy === 'expirationMonth' || event.emittedBy === 'expirationYear') {
if (!event.fields.expirationMonth.isValid || !event.fields.expirationYear.isValid) {
return;
}
} else if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
// Remove any previously applied error or warning classes
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
// Apply styling for a valid field
$(field.container).parents('.form-group').addClass('has-success');
} else if (field.isPotentiallyValid) {
// Remove styling from potentially valid fields
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
} else {
// Add styling to invalid fields
$(field.container).parents('.form-group').addClass('has-warning');
// Add helper text for an invalid card number
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('Looks like this card number has an error.');
}
}
});
hostedFieldsInstance.on('cardTypeChange', function (event) {
// Handle a field's change, such as a change in validity or credit card type
if (event.cards.length === 1) {
$('#card-type').text(event.cards[0].niceType);
} else {
$('#card-type').text('Card');
}
});
$('.panel-body').submit(function (event) {
if($('#nonce').val() == '') {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
console.error(err);
return false;
}
$('#nonce').val(payload.nonce);
$('#checkout_form').submit();
return true;
});
} else {
return true;
}
});
});
});
body {
background-color: #fff;
}
.panel {
width: 80%;
margin: 2em auto;
}
.bootstrap-basic {
background: white;
}
.panel-body {
width: 90%;
margin: 2em auto;
}
.helper-text {
color: #8A6D3B;
font-size: 12px;
margin-top: 5px;
height: 12px;
display: block;
}
/* Braintree Hosted Fields styling classes*/
.braintree-hosted-fields-focused {
border: 1px solid #0275d8;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);
}
.braintree-hosted-fields-focused.focused-invalid {
border: 1px solid #ebcccc;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(100,100,0,.6);
}
#media (max-width: 670px) {
.btn {
white-space: normal;
}
}
<script src="https://js.braintreegateway.com/web/3.36.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.36.0/js/hosted-fields.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<div class="panel panel-default bootstrap-basic">
<div class="panel-heading">
<h3 class="panel-title">Enter Card Details</h3>
</div>
<form class="panel-body" action="checkout.php" method="post" id="checkout_form">
<div class="row">
<div class="form-group col-sm-8">
<label class="control-label">Card Number</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="card-number"></div>
<span class="helper-text"></span>
</div>
<div class="form-group col-sm-4">
<div class="row">
<label class="control-label col-xs-12">Expiration Date</label>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-month"></div>
</div>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-year"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Security Code</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="cvv"></div>
</div>
<div class="form-group col-sm-6">
<label class="control-label">Zipcode</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="postal-code"></div>
</div>
</div>
<input type="hidden" name="payment_method_nonce" id="nonce">
<button type="submit" value="submit" id="submit" class="btn btn-success btn-lg center-block">Pay with <span id="card-type">Card</span></button>
</form>
</div>
Can anyone please help to resolve this issue ?

initializing empty form breaks page; knockoutJS

using knockoutjs I want to have forms that allow infinite choices, but I need the form to display so the user knows it exist. I'm ok with starting with 3 forms, so I'd like to initialize empty objects when the page renders. For some reason, when I initialize one object it breaks my code:
function Task(data) {
this.title=ko.observable(data.title);
this.isDone=ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self=this;
self.tasks=ko.observableArray([]);
// self.tasks.push({'title': ''})
self.newTaskText=ko.observable();
self.incompleteTasks=ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) {
return !task.isDone()
});
});
// Operations
self.addTask=function() {
self.tasks.push(new Task({
title: this.newTaskText()
}));
self.newTaskText("");
};
self.removeTask=function(task) {
self.tasks.destroy(task)
};
self.incompleteTasks=ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(),
function(task) {
return !task.isDone() && !task._destroy
});
});
self.save=function() {
$.ajax(".", {
data: ko.toJSON({
tasks: self.tasks
}),
type: "post",
contentType: "application/json",
success: function(result) {
alert(result)
}
});
};
// load initial state from server, convert to tasks, then add em to self.tasks
$.getJSON(".", function(allData) {
var mappedTasks=$.map(allData, function(item) {
return new Task(item)
});
self.tasks(mappedTasks);
});
self.tasks.push({'title': ''})
}
ko.applyBindings(new TaskListViewModel());
body { font-family: Helvetica, Arial }
input:not([type]), input[type=text], input[type=password], select { background-color: #FFFFCC; border: 1px solid gray; padding: 2px; }
.codeRunner ul {list-style-type: none; margin: 1em 0; background-color: #cde; padding: 1em; border-radius: 0.5em;}
.codeRunner ul li a { color: Gray; font-size: 90%; text-decoration: none }
.codeRunner ul li a:hover { text-decoration: underline }
.codeRunner input:not([type]), input[type=text] { width: 30em; }
.codeRunner input[disabled] { text-decoration: line-through; border-color: Silver; background-color: Silver; }
.codeRunner textarea { width: 30em; height: 6em; }
.codeRunner form { margin-top: 1em; margin-bottom: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="codeRunner">
<h3> Stuff </h3>
<div data-bind="foreach: tasks, visible: tasks().length > 0">
<p data-bind="value: title"></p>
</div>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> -it 's beer time!</span>
<form data-bind="submit: addTask"><button type="submit">Add</button></form>
<script>
</script>
</body>
What is the pattern in knockout to initialize safely with this block of JS? Thank you
The reason you're getting an error is because the isDone property in your initial task was not being set. You also already have a Task viewModel, so why not use it to initialize your array? I've just used an IIFE (immediately-Invoked Function Expression) to initialize new tasks by newing up Task in a for loop. You can do this manually or in whichever way you prefer.
Also be aware of your use of the this keyword. See self.addTask in your code.
Im not sure if this is exactly what you're looking for but I assume you'd need a text input to enter newTaskText or am I missing something? Anyway, this seems to work. Hope is answers your question.
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone || false);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
// self.tasks.push({'title': ''})
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) {
return !task.isDone()
});
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({
title: self.newTaskText(),
isDone: false
}));
self.newTaskText("");
};
self.removeTask = function(task) {
self.tasks.destroy(task)
};
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(),
function(task) {
return !task.isDone() && !task._destroy
});
});
(function(numTasks) {
for (var x = 0; x < numTasks; x++) {
self.tasks.push(new Task({
title: ""
}));
}
})(3)
}
ko.applyBindings(new TaskListViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="codeRunner">
<h3> Stuff </h3>
<input data-bind="textInput: newTaskText" type="text" />
<input data-bind="click: addTask" type="button" value="Add Task" />
<div data-bind="foreach: tasks, visible: tasks().length > 0">
<p data-bind="value: title"></p>
</div>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> -it 's beer time!</span>
<script>
</script>
</body>

gridOption is not receiving my data from controller

I am new to angularjs and I am trying to populate a ui grid with data from a data base. I have tried searching for other issue sbut I haven't found anything similar to my issue online. The table shows just fine but none of my data is populating. I have seen it in the developer tools in Chrome under Source and it appears to be properly formated as a Json object but I cant get it to display anything in the table. I know it is probably something small I am doing or not doing any help would be appreciated.
Below is my controller js
var app = angular.module('skill', ["ui.grid",
"ui.grid.edit",
"ui.grid.selection",
"ui.grid.pagination",
"ui.grid.exporter",
"ui.grid.cellNav"]);
app.controller('SkillEntryController', function ($scope, $http, $interval, uiGridConstants, SkillService) {
$scope.data = [];
SkillService.GetSkills().then(function (d) {
$scope.data = d.data;
}, function () {
alert('Failed');
});
$scope.columns = [
{ name: "SkillName", displayName: "Skill Code", minWidth: 150, width: "33%" },
{ name: "Category", minWidth: 150, width: "33%" },
{ name: "Description", minWidth: 150, width: "33%" }
];
$scope.gridOptions = {
enableSorting: true,
enableRowSelection: true,
enableCellEditOnFocus: true,
exporterHeaderFilterUseName: true,
treeRowHeaderAlwaysVisible: false,
paginationPageSizes: [25, 50, 75],
paginationPageSize: 25,
columnDefs: $scope.columns,
data: $scope.data,
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
}
};
}).factory('SkillService', function ($http) {
var fac = {}
fac.GetSkills = function () {
return $http.get('/Skills/GetSkills');
}
return fac;
});
Here is my factory method:
public JsonResult GetSkills()
{
List<Skill> c = new List<Skill>();
return new JsonResult { Data = c.Select(x => new { x.Category, x.Description, x.SkillCodeID, x.SkillName }), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And here is my cshtml file:
#model IEnumerable<SkillResourceCenterApp.Models.Skill>
#using Newtonsoft.Json;
#{
ViewData["Title"] = "Add Skill";
}
#section scripts{
<link href="~/Content/ui-grid.css" rel="stylesheet" />
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/ui-grid.js"></script>
<script src="~/Scripts/Controller/skill-entry-controller.js"></script>
}
<style>
.ui-grid-cell.cell-center {
text-align: center;
}
.ui-grid-cell.cell-right {
text-align: right;
}
.no-rows {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
background: rgba(0, 0, 0, 0.4);
}
.no-rows .msg {
opacity: 1;
position: absolute;
top: 30%;
left: 33%;
width: 30%;
height: 25%;
line-height: 200%;
background-color: #eee;
border-radius: 4px;
border: 1px solid #555;
text-align: center;
font-size: 24px;
display: table;
}
.no-rows .msg span {
display: table-cell;
vertical-align: middle;
}
</style>
<h3>#ViewData["Title"]</h3>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="container-fluid" ng-app="skill" ng-controller="SkillEntryController">
<div class="row">
<button type="button" ng-click="addNewRow()" class="btn btn-default col-sm-3 col-md-2">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Row
</button>
<button type="button" ng-click="deleteSelected()" class="btn btn-default col-sm-3 col-md-2">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Delete Selected
</button>
<button type="button" ng-click="exportToCSV()" class="btn btn-default col-sm-3 col-md-2">
<span class="glyphicon glyphicon-download" aria-hidden="true"></span> Export to Excel
</button>
<button type="button" ng-click="save()" class="btn btn-primary col-md-offset-4 pull-right col-sm-2">
Save
</button>
</div>
<div class="row">
<div class="grid" ui-grid="gridOptions"
ui-grid-pagination
ui-grid-selection
ui-grid-edit
ui-grid-exporter
ui-grid-cellNav
style="height: 500px;">
<div class="no-rows" ng-show="!gridOptions.data.length">
<div class="msg">
<span>No Results</span>
</div>
</div>
</div>
</div>
</div>
You're missing the field definition in columnDefs. Have a look at https://github.com/angular-ui/ui-grid/wiki/Defining-columns
var columnDefs: [{
field: 'foo',
displayName: 'my foo',
visible: true,
maxWidth: 90,
enableColumnResizing: false,
cellTemplate: "<div>{{row.entity.foo}}</div>"
}];

Categories

Resources