Reading file contents and POSTing in combination with KO mechanism - javascript

I used this tutorial http://www.dotnetcurry.com/aspnet/1006/edit-html-table-crud-knockoutjs-aspnet-webapi to create an editable table with KnockOutJS, without adding the ASP.NET stuff (only the KO part, server-side API is implemented in PHP).
The tutorial works but I added a new feature which doesn't. Instead of outputting a text field I modified the instructions of the author to add a button instead of it in the table. What I am trying to achieve is to read the contents of a file image, store it in a variable and append in POST payload so as to be stored in a blob field in a database table.
Can someone please suggest an alternative way to achieve this or guide me to correct the existing one ? I'm quite a newbie to KnockOutJS and furthermore in Javascript.
var self = this;
//S1:Boolean to check wheather the operation is for Edit and New Record
var IsNewRecord = false;
// filename to be converted into string for uploading
var ImgFile = "";
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
//console.log("In handleFileSelect");
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
ImgFile = readerEvt.target.result;
//console.log("Printing the base64 ...");
//console.log(readerEvt.target.result);
};
reader.readAsBinaryString(file);
}
};
function executeCreateListener() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
//console.log("In if");
document.getElementById('filePicker').addEventListener('change', handleFileSelect, false); // this sh** resolves to null due to KO dynamic nature
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
self.ProductsApallou = ko.observableArray([]);
loadProducts();
//S2:Method to Load all Products by making call to WEB API GET method
function loadProducts() {
alert("Loading Data");
$.ajax({
type: "GET",
url: "http://127.0.0.1/goandwin/store_products.json?retrieve:Store_of_Product=1+Store_Product_id=999+Name=999+Subname=999+Imgname=999+Price=999+Product_Discount=999+Slogan=999+Origin=999+Description=999+Product_Code=999+Category_level_1_id=999+Product_Photo=999",
dataType: "json",
}).done(function(data) {
self.ProductsApallou(data);
}).fail(function(err) {});
alert("Success");
};
//S3:The Product Object
function Product(soproduct, spid, pname, subname, imgname, price, product_disc, slogan, origin, descript, product_code, cbid, pphoto) {
return {
Store_of_Product: ko.observable(soproduct),
Store_Product_id: ko.observable(spid),
Name: ko.observable(pname),
Subname: ko.observable(subname),
Imgname: ko.observable(imgname),
Price: ko.observable(price),
Product_Discount: ko.observable(product_disc),
Slogan: ko.observable(slogan),
Origin: ko.observable(origin),
Description: ko.observable(descript),
Product_Code: ko.observable(product_code),
Category_level_1_id: ko.observable(cbid),
Product_Photo: ko.observable(pphoto)
}
};
//S4:The ViewModel where the Templates are initialized
var ProdViewModel = {
readonlyTemplate: ko.observable("readonlyTemplate"),
editTemplate: ko.observable()
};
//S5:Method to decide the Current Template (readonlyTemplate or editTemplate)
ProdViewModel.currentTemplate = function(tmpl) {
return tmpl === this.editTemplate() ? 'editTemplate' : this.readonlyTemplate();
}.bind(ProdViewModel);
//S6:Method to create a new Blank entry When the Add New Record button is clicked
ProdViewModel.addnewRecordApallou = function() {
self.ProductsApallou.push(new Product(1, "auto", "default", "default", "default", 0, 0, "default", "default", "default", "default", 1, "default"));
IsNewRecord = true;
};
//S7:Method to Save the Record (This is used for Edit and Add New Record)
ProdViewModel.saveProduct = function(d) {
var Prod = {};
//console.log(d);
Prod.Store_of_Product = d.Store_of_Product;
Prod.Store_Product_id = d.Store_Product_id;
Prod.Name = d.Name ? d.Name : null;
Prod.Subname = d.Subname ? d.Subname : null;
Prod.Imgname = d.Imgname ? d.Imgname : null;
Prod.Price = d.Price ? d.Price : 0.0;
Prod.Product_Discount = d.Product_Discount ? d.Product_Discount : 0;
Prod.Slogan = d.Slogan ? d.Slogan : null;
Prod.Origin = d.Origin ? d.Origin : null;
Prod.Description = d.Description ? d.Description : null;
Prod.Product_Code = d.Product_Code ? d.Product_Code : null;
Prod.Category_level_1_id = d.Category_level_1_id ? d.Category_level_1_id : 1;
//console.log("Printing imgfile ...");
//console.log(ImgFile);
// <---- HERE what I am trying to achieve, if possible
if (ImgFile) {
Prod.Product_Photo = ImgFile; //take the string produced after uploaded
} else {
Prod.Product_Photo = d.Product_Photo; //take the string as it was
}
// ---->
//Edit the Record
if (IsNewRecord === false) {
$.ajax({
type: "PUT",
url: "http://127.0.0.1/goandwin/store_products/" + Prod.Store_Product_id,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: Prod
}).done(function(data) {
alert("Record Updated Successfully " + data.status);
ProdViewModel.reset();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
//The New Record
if (IsNewRecord === true) {
var tmp = Prod;
delete tmp.Store_Product_id; //remove the PK which is auto
IsNewRecord = false;
$.ajax({
type: "POST",
url: "http://127.0.0.1/goandwin/store_products",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: tmp
}).done(function(data) {
alert("Record Added Successfully " + data.status);
ProdViewModel.reset();
loadProducts();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
}
//S8:Method to Delete the Record
ProdViewModel.deleteProduct = function(d) {
$.ajax({
type: "DELETE",
url: "http://127.0.0.1/goandwin/store_products/" + d.Store_Product_id
}).done(function(data) {
//console.log(d.Store_Product_id);
alert("Record Deleted Successfully " + data.status);
ProdViewModel.reset();
loadProducts();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
//S9:Method to Reset the template
ProdViewModel.reset = function(t) {
this.editTemplate("readonlyTemplate");
};
ko.applyBindings(ProdViewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="tab-content">
<div id="Apallou" class="tab-pane fade in inactive">
<table class="table table-striped table-bordered table-hover" id="dataTables-exampleApallou">
<thead>
<tr>
<th>Store_of_Product</th>
<th>Store_Product_id</th>
<th>Name</th>
<th>Subname</th>
<th>Imgname</th>
<th>Price</th>
<th>Product_Discount</th>
<th>Slogan</th>
<th>Origin</th>
<th>Description</th>
<th>Product_Code</th>
<th>Category_level_1_id</th>
<th>Product_Photo</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="template: { name: currentTemplate, foreach: ProductsApallou }"></tbody>
</table><br><input type="button" value="Add New Record" data-bind="click: function () { ProdViewModel.addnewRecordApallou(); }" /><br></div>
</div>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<script type="text/html" id="readonlyTemplate">
<tr>
<td><span data-bind="text: Store_of_Product"></span></td>
<td><span data-bind="text: Store_Product_id"></span></td>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: Subname"></span></td>
<td><span data-bind="text: Imgname"></span></td>
<td><span data-bind="text: Price"></span></td>
<td><span data-bind="text: Product_Discount"></span></td>
<td><span data-bind="text: Slogan"></span></td>
<td><span data-bind="text: Origin"></span></td>
<td><span data-bind="text: Description"></span></td>
<td><span data-bind="text: Product_Code"></span></td>
<td><span data-bind="text: Category_level_1_id"></span></td>
<td><img width="60px" height="70px" data-bind="attr:{src: Product_Photo}" /></td>
<td>
<input type='button' value='Edit' data-bind='click: function () { ProdViewModel.editTemplate($data);}'>
</td>
<td>
<input type='button' value='delete' data-bind='click: function () { ProdViewModel.deleteProduct($data); }'>
</td>
</tr>
</script>
<script type="text/html" id="editTemplate">
<tr>
<td><input type='text' data-bind='value: $data.Store_of_Product' /></td>
<td><input type='text' data-bind='value: $data.Store_Product_id' disabled='disabled' /></td>
<td><input type='text' data-bind='value: $data.Name' /></td>
<td><input type='text' data-bind='value: $data.Subname' /></td>
<td><input type='text' data-bind='value: $data.Imgname' /></td>
<td><input type='text' data-bind='value: $data.Price' /></td>
<td><input type='text' data-bind='value: $data.Product_Discount' /></td>
<td><input type='text' data-bind='value: $data.Slogan' /></td>
<td><input type='text' data-bind='value: $data.Origin' /></td>
<td><input type='text' data-bind='value: $data.Description' /></td>
<td><input type='text' data-bind='value: $data.Product_Code' /></td>
<td><input type='text' data-bind='value: $data.Category_level_1_id' /></td>
<td>
<div><label for="filePicker">Choose a file:</label><input type="file" id="filePicker"></div>
</td>
<td>
<input type="button" value="Save" data-bind="click: ProdViewModel.saveProduct" />
</td>
<td>
<input type="button" value="Cancel" data-bind="click: function () { ProdViewModel.reset(); }" />
</td>
</tr>
</script>
I know my explanation of what I'm trying to do is somehow vague, so feel free to ask questions to make things clear. My project lies here if someone wishes to check it out (dpesios, test).

Related

How can I select all checkboxes in mvc

This code below select only one by one checkbox, how can I transform this code so I can select all checkboxes by one click, but I need my variables to stay defined.
$('.checktip').click(function () {
var iduser = $('.iduser').val();
var idtip = $(this).attr('idtip');
var che = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.OrgUnits,
data: { iduser: iduser, idtip: idtip, che: che },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});
I using this variables for controller where I save this values in database when I check them or unchecked.
Here is my html code
<input type="hidden" value="#ViewBag.iduser" id="iduser" />
<hr />
<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
//Checkbox for check all *(NOT IMPLEMENTED)*
<input type="checkbox" id="box" name="checkAll" />
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
#*#Html.CheckBox(item.id.ToString(), item.iduser == ViewBag.iduser ? true : false, new { idtip = item.idtip, #class = "checktip" })*#
<div class="pure-checkbox">
<input type="checkbox" idtip="#item.idtip" class="checktip" checked="#(item.iduser == ViewBag.iduser ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
Following code should work with your code
$('#box').click(function(){ $('.checktip').prop('checked', true); }};

How to render the AJAX response in the JSP/HTML element (returned from db)

enter image description hereenter image description hereHow to render a ajax response from db (map) in jsp screen
I am getting response in browser console but not sure how to render it in jsp on the browser screen like a table or any better suggestion
$('#submit_btn').click(function(){
var problemId = $('#search_data').val();
$.ajax({
type: "GET",
dataType : "json",
url : "http://localhost:8080/bugs/" + bugId,
success: function(data){
$("#response").html(data);
console.log('response data',data);
},
error : function(err){
console.log('error',err)
}
});
});
JSP
<body>
<div>
<div>
<h1>Lookup from Oracle database</h1>
Click on this <strong>link</strong> to visit home page.
</div>
<div>
<h2>${message}</h2>
<table>
<tr>
<td>Search Category:</td>
<td>
<select name="searchcategories">
<option value="-1">-Select Category-</option>
<option value="bug">bug</option>
<option value="attachment">attachment</option>
</select>
</td>
</tr>
<tr>
<td>Entity Id:</td>
<td><input type="text" name="bugId" id="search_data" class="form-control" placeholder="Search bug no..">
</td>
</tr>
<tr>
<td></td>
<td><button type="button" id="submit_btn" onclick="">Search</button>
</td>
</tr>
<tr>
<td>Bug Id:</td>
<td><input type="text" id="bugId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
$('#submit_btn').click(function(){
var bugId = $('#search_data').val();
$.ajax({
type: "GET",
dataType : "json",
url : "http://localhost:8080/bugs/" + bugId,
success: function(data){
$("#response").html(data);
console.log('response data',data);
var bugDetails = data;
renderDetails(data);
},
error : function(err){
console.log('error',err)
}
});
});
function renderDetails(data)
{
var id = document.getElementById("bugId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.innerHTML = data.bugId;
name.innerHTML = data.probStateName;
priority.innerHTML = data.priorityName;
};
</script>
</html>
below is the response object that I see in console that has data fetched from backend. I want to render this ajax response below the search box
[Log] response data (oracle-lookup, line 65)
Object
data: {bugId: 298, stateCode: "2", …}
Object Prototype
You can populate data to any field from the following code. Probably best to also add a check to see whether the returned values are not empty.
<script type="text/javascript">
var bugDetails;
$(document).ready(function(){
$("#submit_btn").click(function(event){
event.preventDefault();
var bugId = document.getElementById("search_data").value;
$.ajax({
type: 'GET',
url: "http://localhost:8080/bugs/" + bugId,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
bugDetails = data;
renderDetails(bugDetails);
alert(data);
alert(jqXHR.status);
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(jqXHR.status);
alert(errorThrown);
}
});
});
});
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
</script>
So now your code should be like this,
<body>
<div>
<div>
<h1>Lookup from Oracle database</h1>
Click on this <strong>link</strong> to visit home page.
</div>
<div>
<h2>${message}</h2>
<table>
<tr>
<td>Search Category:</td>
<td>
<select name="searchcategories">
<option value="-1">-Select Category-</option>
<option value="bug">bug</option>
<option value="attachment">attachment</option>
</select>
</td>
</tr>
<tr>
<td>Entity Id:</td>
<td><input type="text" name="bugId" id="search_data" class="form-control" placeholder="Search bug no..">
</td>
</tr>
<tr>
<td></td>
<td><button type="button" id="submit_btn">Search</button>
</td>
</tr>
<tr>
<td>Bug Id:</td>
<td><input type="text" id="problemId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var bugDetails;
$(document).ready(function(){
$("#submit_btn").click(function(event){
event.preventDefault();
var bugId = document.getElementById("search_data").value;
$.ajax({
type: 'GET',
url: "http://localhost:8080/bugs/" + bugId,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
bugDetails = data;
renderDetails(bugDetails);
alert(data);
alert(jqXHR.status);
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(jqXHR.status);
alert(errorThrown);
}
});
});
});
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
</script>
</html>
I have created Text Fields to fetch the data coming from AJAX call. Make sure you are using these ids.
<tr>
<td>Bug Id:</td>
<td><input type="text" id="problemId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
And when data comes from the AJAX call it will fetch to above fields using this method,
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
So what you need to care about is make sure text field ids are correct.

set value to jquery datatable after updating row in spring mvc with backbone.js

My project having a problem that when table row button clicked it will appear on the html input typ="text" for user updation.Updation running successfully.What i need is,when user clicked update button the updated row must replace with new row + another button for again updation.
html
<h1>Time Management</h1>
<fieldset>
<h3>Update Test!</h3>
<form action="#" th:action="#{/admin/updateTest.html}"
th:object="${test}" id="formTest">
<table>
<tr>
<td>Test Name</td>
<td><input type="text" id="testName" required="required"
th:field="*{name}" disabled="disabled"/></td>
</tr>
<tr>
<td>Max No.of Questions</td>
<td><input type="text" id="questionNo" required="required"
th:field="*{maxNoQuestions}" onKeyUp="numericFilter(this);" /></td>
</tr>
<tr>
<td>Max Time</td>
<td><input data-format="hh:mm:ss" type="text" id="testTime"
required="required" th:field="*{maxTime}" />
</td>
</tr>
<tr>
<td><input type="button" value="Update" id="btnUpdate" /> <input
type="hidden" th:field="*{id}" id="hdnTestId" /></td>
<td><label id="statusMsg"
style="color: red; size: portrait; font-size: small;"></label></td>
</tr>
</table>
</form>
</fieldset>
<table id="tests"
style="cellpadding: 0px; cellspacing: 0px; border: 0px;">
<thead>
<tr>
<th width="5%">#</th>
<th align="left">Test Name</th>
<th align="left">Max No.of Questions</th>
<th align="left">Max Time</th>
<th align="left"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
below is my backbone script for updation.
script
var TimeManagementView = Backbone.View.extend({
sTable:null,
// target item.
el : $("#adminContentOuterPnl"),
render : function() {
var data = {};
// template
var compiledTemplate = _.template(timeManagementTemplate, data);
// append the item to the view's target
this.$el.html(compiledTemplate);
sTable = $('#tests').dataTable({
"aoColumns" : [ null, null, null, null, null ],
"sPaginationType" : "full_numbers"
});
//load data from db to table.
this.loadSavedTests();
},
// Event Handlers
events : {
"click #btnUpdate" : "updateTest"
},
loadSavedTests : function() {
$('#tests tbody tr').remove();
$('#tests tbody').append('<tr><td><h4>...Loading...</h4></td></tr>');
//Load the data in using jQuerys ajax call
$.ajax({
type : 'POST',
url : 'loadAllTests.html',
success: function(responseData) {
sTable.fnClearTable();
if(responseData.length > 0){
$.each(responseData, function(index,item) {
var rowCount = index+1;
sTable.fnAddData( [ rowCount,item['name'], item['maxNoQuestions'], item['maxTime'],'<input type="image" src="../resources/img/icons/edit.png" alt="Edit" onclick="editTest('+item['id']+',this); return false;" />' ]);
});
}
}
});
},
updateTest : function(){
$('#statusMsg').text("");
if($('#testName').val()==''){
$('#statusMsg').text("Test Name Can't Be Null");
return false;
}
if($('#questionNo').val()==''){
$('#statusMsg').text("Question No. Can't Be Null");
return false;
}
if($('#testTime').val()==''){
$('#statusMsg').text("Test Time Can't Be Null");
return false;
}
$('#statusMsg').text("Updating...");
$("#formTest").ajaxForm({
success : function(status) {
if (status == 1) {
// addRowToTests(status.object);
testRow.find("td").eq(0).text($('#testName').val());
testRow.find("td").eq(1).text($('#questionNo').val());
testRow.find("td").eq(2).text($('#testTime').val());
$('#testName').val('');
$('#questionNo').val('');
$('#testTime').val('');
$('#statusMsg').text("Data Updated!");
}
},
dataType : 'json'
}).submit();
}
});
return new TimeManagementView;
});
$("#formTest").ajaxForm({
success : function(status) {
console.log(status.statusCode);
if (status.statusCode == 0) {
testRow.find("td").eq(1).text('');
testRow.find("td").eq(2).text('');
testRow.find("td").eq(3).text('');
testRow.find("td").eq(4).text('');
testRow.find("td").eq(1).text($('#testName').val());
testRow.find("td").eq(2).text($('#questionNo').val());
testRow.find("td").eq(3).text($('#testTime').val());
testRow.find("td").eq(4).html('<input type="image" src="../resources/img/icons/edit.png" alt="Edit" onclick="editTest('+status.object.id+'); return false;" />');
$('#testName').val('');
$('#questionNo').val('');
$('#testTime').val('');
$('#statusMsg').text("Data Updated!");
}else{
$('#statusMsg').text("No Change");
}
},
dataType : 'json'
}).submit();

How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?

so here's my situation. I have a form that gives the user the ability to add any number of rows to the form and input more data into those newly created rows (using javascript). I HAVE THIS ALREADY set up in the following code (I am using index.html, js/scripts.js and a php/upload.php files, all are externally linked, including an external CSS):
INDEX.HTML
<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>
<input type="hidden" id="co_city">
<input type="hidden" id="co_state">
<input type="hidden" id="co_zipcode">
<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
<td><select id="company_name"></select></td>
<td><input id="co_name" type="text"></td>
<td><input type="submit" value="Get GPS" onclick="gpslookup()"></td>
<td><input id="co_lat" type="text"></td>
<td><input id="co_long" type="text"></td>
<td><input id="co_address" type="text"></td>
</tr>
</table>
<table id="tabledata">
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
<!--Begin Rows-->
<tr>
<td><input type="checkbox"></td>
<td><input id="border_location" type="text" name="txt[]"></td>
<td><input id="cable_location" type="text" name="txt[]"></td>
<td><input id="vault_direction" type="text" name="txt[]"></td>
<td><input id="cable_type" type="text" name="txt[]"></td>
<td><input id="cable_size" type="text" name="txt[]"></td>
<td><input id="cable_gauge" type="text" name="txt[]"></td>
<td><input id="vertical" type="text" name="txt[]"></td>
<td><input id="jumpers" type="text" name="txt[]"></td>
<td><input id="protectors" type="text" name="txt[]"></td>
<td><input id="metered_dist" type="text" name="txt[]"></td>
<td><input id="comments" type="text" name="txt[]"></td>
</tr>
</table>
<input id="addrow_btn" type="submit" value="Add New Row" onclick="addRow(); return false;" />
<input id="delrow_btn" type="submit" value="Delete Row" onclick="deleteRow(); return false;" />
<input id="submit" type="submit" value="Submit" onclick="uploaddata(); return false;" />
</body>
</html>
As for the backend, I ONLY have the PHP and server side scripts able to submit information for that first row using the below code:
JAVASCRIPT FILE
function addRow() {
var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
//UPLOAD DATA
//Global variables
var survey = {
'co_name' : "",
'co_lat' : "",
'co_long' : "",
'co_address' : "",
'border_location' : "",
'cable_location' : "",
'vault_direction' : "",
'cable_type' : "",
'cable_size' : "",
'cable_gauge' : "",
'vertical' : "",
'jumpers' : "",
'protectors' : "",
'metered_dist' : "",
'comments' : "",
'company_name' : "",
'co_city' : "",
'co_state' : "",
'co_zipcode' : ""
}
function uploaddata() {
//Read all of the data from the page
for (eID in survey) {
survey[eID] = document.getElementById(eID).value;
}
//Insert data into database
$.ajax({
type: 'POST',
url: './php/upload_survey.php',
data: survey,
async: false,
dataType: 'text',
success: function() {
alert("Thank you. Your survey has been submitted.");
window.location.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error... " + textStatus + "\n" + errorThrown);
}
});
}
PHP FILE
//Assign passed parameters
$co_name = $_POST['co_name'];
$co_lat = $_POST['co_lat'];
$co_long = $_POST['co_long'];
$co_address = $_POST['co_address'];
$border_location = $_POST['border_location'];
$cable_location = $_POST['cable_location'];
$vault_direction = $_POST['vault_direction'];
$cable_type = $_POST['cable_type'];
$cable_size = $_POST['cable_size'];
$cable_gauge = $_POST['cable_gauge'];
$vertical = $_POST['vertical'];
$jumpers = $_POST['jumpers'];
$protectors = $_POST['protectors'];
$metered_dist = $_POST['metered_dist'];
$comments = $_POST['comments'];
$txt = $_POST['txt'];
$stringLogInfo = "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
log_audit($logAuditFile, $logModule, $stringLogInfo);
//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Insert Survey Form Information into the database
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.$value.'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$sql='INSERT INTO table_name ('.$fieldlist.') VALUES ('.$vallist.')';
mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());
My objective up to this point, having already everything else sort of ready, is to be able to loop through all the data in the form, according to however many rows they create and submit all those new row values into the SQL Database into SEPARATE rows. Please Advise!
Focusing on the HTML part of this question here is an approach to grow a form dynamically:
First the HTML:
<table id="tabledata">
<thead>
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input name="selected" type="checkbox" /></td>
<td><input name="border_location" type="text" /></td>
<td><input name="cable_location" type="text" /></td>
<td><input name="vault_direction" type="text" /></td>
<td><input name="cable_type" type="text" /></td>
<td><input name="cable_size" type="text" /></td>
<td><input name="cable_gauge" type="text" /></td>
<td><input name="vertical" type="text" /></td>
<td><input name="jumpers" type="text" /></td>
<td><input name="protectors" type="text" /></td>
<td><input name="metered_dist" type="text" /></td>
<td><input name="comments" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button id="ActionSubmit">Submit</button>
And This JavaScript:
$(function () {
var addInputRow = function () {
$('#input').append($('#template').html());
};
addInputRow();
$('#ActionAddRow').on('click', addInputRow);
$('#ActionSubmit').on('click', function () {
var data = $('#input tr').map(function () {
var values = {};
$('input', $(this)).each(function () {
if (this.type === 'checkbox') {
values[this.name] = this.checked;
} else {
values[this.name] = this.value;
}
});
return values;
}).get();
$.post('/echo/json/', {
json: JSON.stringify(data),
delay: 1
}).done(function (response) {
alert("POST success");
console.log(response);
});
});
});
And then this CSS:
tbody#template {
display: none;
}
Produces this demo
Here is a breakdown of what is happening. First the table element can define mutiple bodies, so I've added the HTML of an empty row of inputs and hidden (with CSS) it in a tbody with the ID of template. Using JavaScript, I then define a simple function that just appends the contents of that row to the tbody with the ID of inputs and I bind that function to the click event of a button. Then because the inputs tbody is starts out as empty I call that function once. Then for submitting the form, I select all rows of the inputs tbody and iterate over the inputs found inside them. Next, I am combining them into one large array of JavaScript objects with each element representing a row, and finally I'm posting this showing a round trip with this data from the client to the server (I'm using JSON2.js to serialize the data). Your PHP page would pick up from here to check them on the server, and (using a prepared statement) insert valid rows into the database.
Your PHP would take the POSTed values like this:
$value = json_decode($_POST['json']);
And treat the submitted data as an associative array. This approach uses an AJAX Form Post, so the response of the PHP page should be a valid JSON with a structure something like this:
{Success: true}

jqgrid can't display data from a variable

I have here a javascript code. What I want is that I want to store the data result from this url:
'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)), to my variable 'tempIncDed', and display that data in my jqgrid.
My question here now is, why is that though when i alert the variable tempIncDed, it shows that it stores the correct data, but it does not display in my jqgrid?
Did I miss something in my code?
Below is my js code:
var tempIncDed = [];
$(document).ready( function() {
$("#tblIncDed").jqGrid({ data: tempIncDed,
datatype: "local",
colNames:['Code','Description', 'Taxable','Amount'],
colModel:[
{name:'ded_code',width: 85},
{name:'ded_desc'},
{name:'taxable',width: 95},
{name:'amount', formatter:'currency', align:'right',width: 85}
],
rowNum:20,
viewrecords: true,
rowList:[20,50,100],
ppager: '#tblIncDedPager',
viewrecords: true,
caption: "Details"
});
$( "#btnEarn" ).click(function() {
var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
var dataTempEarn = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"per_id":$("#payPeriod").val(),
"emp_no":empNo
};
$.ajax({
type: 'GET',
url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
var resLen = data.result.length;
tempIncDed = JSON.stringify(data.result);
alert('this is the tempDed ' + tempIncDed);
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempIncDed}
).trigger("reloadGrid");
}
}
});
$("#dialOtherIncDed").dialog( "open" );
$("#dialOtherIncDed").attr("name","earnings");
});
})
This is the tempDed sample data: [{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
Some of my html code:
<!--master grid-->
<div style="width:100%">
<table id="tblPayroll"></table>
<div id="tblPayrollPager"></div>
</div>
<!--dialog that contains the table for other earnings, deductions, loans-->
<div id="dialOtherIncDed" style="width:100%">
<table id="tblIncDed"></table>
<div id="tblIncDedPager"></div><br><br>
Total amount: <b><span id="totalAmnt"></span></b>
</div>
<!--dialog that contains the dialog edit earnings, deductions, loans-->
<div id="editIncDed"">
<table>
<tr>
<span id="incDed_name"></span>
<td>Amount:</td>
<td><input class="numeric" type="text" id="amount" value = ""/></td></tr>
</table>
</div>
<!--edit-->
<div id="dialogPayrollEdit" title="Payroll Entry">
<table>
<tr>
<td>Payroll Period:</td>
<td><b><span id="periodDateL" style="color:blue"></span></b></td>
<td>Type:</td><td><b><span id="rateType" style="color:blue"></span></b></td>
<td>Rate:</td><td><b><span id="payRate" style="color:blue"></span></b></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><b><span id="empName" style="color:blue"></span></b></td>
</tr>
</table>
<hr/>
<fieldset><legend>Payroll Details</legend>
<p><center><b>EARNINGS</b></center></p>
<table>
<tr>
<td>
....
</td>
<td>
<table >
<tr...tr>
<tr>...</tr>
<tr>...</tr>
<tr><td>Other earnings</td><td><input class="numeric" style="width:60px" id="mOther_amnt" value = ""/></td><td><input type='button' value='...' id="btnEarn"></td></tr>
<tr><td><b>GROSS PAY</b></td><td></td><td><b><span style="width:60px;color:blue" id="grossPay"/></b></td></tr>
</table>
</td>
</tr>
</table>
<hr/>
<p><center><b>DEDUCTIONS</b></center></p>
<table width = "100%">
<tr>
<td>
....
</td>
<td>
<table >
<tr>
<td>Other deductions</td>
<td><input class="numeric" style="width:60px;color:black" id="mOther_ded" value = "" disabled/></td>
<td><input type='button' value='...' id="btnDed"/></td>
</tr>
<tr>
<td>Advances/Loans</td>
<td><input class="numeric" style="width:60px;color:black" id="mLoan_ded" value = "" disabled/></td>
<td><input type='button' value='...' id="btnLoan"></td>
</tr>
<tr></tr>
<tr></tr>
<tr><td><b>NET PAY</b></td><td></td><td><b><span class="numeric" style="width:60px;color:blue" id="netPay" value = "" disabled/></b></td><td></td></tr>
</table>
</td>
</tr>
</table>
<br>
</fieldset><br>
Suggest lowest NET PAY >>> <input type="text" id="lowNetPay" value = "" style="width:80px;color: black" value='0.00' disabled/>
</div><br><br>
<br><br>
<button id="btnPayrollEdit">Edit</button>
The btnLoan, btnDed, and btnEarn will be using the same grid. I also used the variable tempIncDed to save the returned data from ajax..
I've finally solved my own problem. Lets say for example I have this data stored in var tempInc,
[{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
This data was an output from ajax request, when the button btnEarn is click.
Here's my javascript code of btnEarn.
var tempInc = []; // global variable
$( "#btnEarn" ).click(function() {
$("#tblIncDed").clearGridData();
var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
var dataTempEarn = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"per_id":$("#payPeriod").val(),
"emp_no":empNo
};
$.ajax({
type: 'GET',
url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
dataType: primeSettings.ajaxDataType,
success: function(data) {
var tempIncDed = [];
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data.result, function(rowIndex, rowDataValue) {
var fldName = rowDataValue;
tempInc[rowIndex] = fldName;
});
var resLen = data.result.length;
$("#totalAmnt").text(data.result[resLen -1].mTot_amnt);
$("#disTemp").text((JSON.stringify(tempInc)));
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempInc}
).trigger("reloadGrid");
}
}
});
$("#dialOtherIncDed").dialog( "open" );
$("#dialOtherIncDed").attr("name","earnings");
});
Everytime I click that button, it will send ajax request to the server. The data returned (particularlly the object since i have an array of objects) will be saved in global variable, tempInc. After that, I have this code:
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempInc}
).trigger("reloadGrid");
that will display the tempInc in my jqgrid. Hope this will help someone out there.

Categories