WooCommerce Add-ons information in Google Sheets - javascript

I am exporting WooCommerce orders to a google sheets using WooCommerce Webhooks and Apps Script
I have two queires
1) How do I reference WooCommerce "add-ons" data
2) Parent order ID is not showing in google sheet
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var timestamp = new Date();
var order_number = myData.number;
var parent_id= myData.parent_id;
var order_status = myData.status;
var billing_first_name = myData.billing.first_name;
var billing_last_name = myData.billing.last_name;
var billing_phone = myData.billing.phone;
var billing_email = myData.billing.email;
var order_total = myData.total;
var billing_address_1 = myData.billing.address_1;
var billing_address_2 = myData.billing.address_2;
var billing_city = myData.billing.city;
var billing_address = billing_address_1 + ", " + billing_address_2 + ", " + billing_city;
var billing_postcode = myData.billing.postcode;
var shipping_first_name = myData.shipping.first_name;
var shipping_last_name = myData.shipping.last_name;
var shipping_address_1 = myData.shipping.address_1;
var shipping_address_2 = myData.shipping.address_2;
var shipping_city = myData.shipping.city;
var shipping_address = shipping_address_1 + ", " + shipping_address_2 + ", " + shipping_city;
var shipping_postcode = myData.shipping.postcode;
var lineitems=""
for (i in myData.line_items)
{
var product_name = myData.line_items[i].name;
var itemName = myData.line_items[i].name;
var quantity = myData.line_items[i].quantity;
var linetotal = myData.line_items[i].total;
var product_items = quantity + " x " + itemName + ": £"+linetotal +"\n";
var lineitems =lineitems+product_items;
}
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_number,parent_id,order_status,billing_first_name,billing_last_name,billing_phone,billing_email,lineitems,order_total,billing_address,billing_postcode,shipping_first_name,shipping_last_name,shipping_address,shipping_postcode]);
}

What is missing from your question is:
We don't know from from where and how you get the order data in javascript
We don't know where you need to display the order Number.
So we can only make a generic answer.
Also note that asking multiple questions at once is not allowed in StackOverFlow.
1) The WooCommerce add-ons data within an WooCommerce order is stored as order item custom meta data:
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
foreach( $order->get_items() as $item_id => $item ){
// Get the special meta data in an array:
$meta_data = $item->get_meta_data();
echo '<pre>'; print_r($meta_data); echo '<pre>'; // Testing raw output
// Get all additional meta data (formatted in an unprotected array)
$formatted_meta_data = $item->get_formatted_meta_data( ' ', true );
echo '<pre>'; print_r($formatted_meta_data); echo '<pre>'; // Testing raw output
// Get the specific meta data from a meta_key:
$meta_value = $item->get_meta( 'custom_meta_key' );
}
Related: Get Order items and WC_Order_Item_Product in WooCommerce 3
2) To get the parent order number from a subscription you will use:
From the subscription ID we can get the order ID very easily:
$order_id = wp_get_post_parent_id( $subscription_id );
From a WC_Subscription Object we can also get the order ID very easily:
$order_id = $subscription->get_parent_id();
Then from this order ID you can get the order number with:
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order_mumber = $order->get_order_number();
or with:
$order_mumber = get_post_meta( $order_id, _order_number, true );

Related

How to update multiple table rows into mysql table when click save button using Jquery and PHP?

I have a myql table name - invoice_details
invoice_number received_amount receiptID
1000 0.00
1001 0.00
1005 0.00
I have a html table
When clicking the save button, update invoice_details table with received amount and receiptID where invoice number in the html table row (1001,1005) Multiple rows will be there in html table.
appending this html table code:
$('#invoicelist_receipt').find('tbody').remove();
$.each($("input[name='myTextEditBox[]']:checked"), function() {
var data = $(this).parents('tr:eq(0)');
// values += $(data).find('td:eq(0)').text() + "," + $(data).find('td:eq(1)').text() + "," + $(data).find('td:eq(2)').text() + ",";
var t1 = $(data).find('td:eq(0)').text();//invoice date
var t2 = $(data).find('td:eq(1)').text();//invoice no
var t3 = $(data).find('td:eq(2)').text();//invoice amt
trtoggle += "<tr><td class=''>" + t1 + "</td><td name='invoice_no_receipt[]' class='invoice_no_receipt'>" + t2 + "</td><td class=''>" + t3 + "</td><td class=''><input class='form-control invoice_amt_receipt' type='number' data-type='invoice_amt_receipt' id='invoice_amt_receipt_1' name='invoice_amt_receipt[]' for='1'/></td></tr>";
//values.push({ 'invoicedate':$(data).find('td:eq(0)').text(), 'invoiceno':$(data).find('td:eq(1)').text() , 'invoiceamount':$(data).find('td:eq(2)').text()});
});
$("#invoicelist_receipt").last().append(trtoggle);
when button clicks:(creating a new receipt)
var invoice_no_receipt = []; //where invoice no = 1000,1001,1005 etc..
var invoice_amt_receipt = [];//this received amount i have to update into database - invoice details table
$('.invoice_no_receipt').each(function() {
invoice_no_receipt.push($(this).val());
});
$('.invoice_amt_receipt').each(function() {
invoice_amt_receipt.push($(this).val());
});
$.ajax({
url: base_url + "index.php/welcome/savereciptfinal/",
type: "POST",
data: {
"getinvnumber": invoice_no_receipt,
"getinv_recived_amount": invoice_amt_receipt
},
success: function(data) {
}
});
PHP Codeigniter code
public function savereciptfinal()
$value2 = "0001"; //autogenerate number
$value = $value2;
$data = array(
'rece_No' => $value
);
$insert_id = 0;
if ($this->db->insert("receipt_details", $data)) {
$insert_id = $this->db->insert_id();
}
$data2 = array(
'rece_Amt' => $this->input->post('getrece_amt'),
'receipt_ID' => $value2; //the above auto generated number i need to update invoice_details for column receiptID
);
$this->db->where('invoice_No ', $inv_id);
$this->db->update('invoice_details', $data2);
}
You can get ideas from this code and sync it with your own code
First clear this script:
$('#invoicelist_receipt').find('tbody').remove();
$.each($("input[name='myTextEditBox[]']:checked"), function() {
var data = $(this).parents('tr:eq(0)');
var t1 = $(data).find('td:eq(0)').text();//invoice date
var t2 = $(data).find('td:eq(1)').text();//invoice no
var t3 = $(data).find('td:eq(2)').text();//invoice amt
trtoggle += "<tr><td class=''>" + t1 + "</td><td name='invoice_no_receipt[]' class='invoice_no_receipt'>" + t2 + "</td><td class=''>" + t3 + "</td><td class=''><input class='form-control invoice_amt_receipt' type='number' data-type='invoice_amt_receipt' id='invoice_amt_receipt_1' name='invoice_amt_receipt[]' for='1'/></td></tr>";
});
$("#invoicelist_receipt").last().append(trtoggle);
Set your save button id instead of 'your_save_button_id'
You can see how send your invoice details in js
$(document).on('your_save_button_id', 'click', function(){
var invoice_no_receipt = [];
$('.invoice_no_receipt').each(function() {
// Json format to add product invoice detail
var invoice_detail = new Object();
// Get invoice number
invoice_detail.no = $(this).text();
// Get parent tr
var parent_tr = $(this).closest('tr');
// Get amount
invoice_detail.amt = $(parent_tr).find('invoice_amt_receipt').val();
// Add invoice detail to invoice_no_receipt
invoice_no_receipt.push(invoice_detail);
});
$.ajax({
url: base_url + "index.php/welcome/savereciptfinal/",
type: "POST",
data: {
"invoice_no_receipt": invoice_no_receipt
},
success: function(data) {
}
});
})
You can see how can get your invoice detail in PHP
IN Your PHP code in ajax function
// Get invoice_no_receipt
$invoice_no_receipt = $_POST('invoice_no_receipt');
foreach( $invoice_no_receipt as $item )
{
// Get invoice number
$invoice_no = intval($item['no']);
// Get invoice amount
$invoice_amt = floatval($item['amt']);
// Update your invoice in db one by one and by use from these variable
// Your update function
}

how to update google Sheet to MySQL

MY table :test_tbl
i need to apply Where condition .
In that code update all row in Price Column .
code:
function UdateRecords() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
conn.setAutoCommit(false);
var start = new Date();
var update = conn.prepareStatement("UPDATE test_table SET Price ='" + "100" + "'");
update.addBatch();
var batch_1 = update.executeBatch();
}
i need to update row where item="cake" replace item="Pizza" Quantity="10" Price="500" and total_price="5000"
UPDATE test_table
SET item = "Pizza"
, Quantity = 10
, Price = 500
, total_price = 5000
WHERE item = "cake"

Event listener code won't execute function as expected

I am trying to write a small javascript function which takes data from OpenSignal and then displays it in an html table.
This worked fine up until the point where I tried to make it user friendly by adding in an html form to accept the postcodes input. I tried to avoid using PHP to do this as my client won't have this installed.
I am adding an event listener to the submit button to detect when the form data has been submitted. I am then taking this and validating the string contains valid postcode(s). If they're invalid the program spits out an alert which says "Sorry but you seem to have entered an incorrect postcode.".
If not then I am taking the postcodes and passing them into my function processPostcodesOnServer(). The thing is that this doesn't work inside the event listener. When I pass postcodes in manually using javascript arrays and call the function outside of the event listener everything works fine. When I put it in the event listener it simply doesn't work. I have checked all the inputs to the function are correct and have stepped through the whole program numerous times and cannot find out what is causing the problem. It seems to me this is just another case of Javascripts random behaviour.
Can anyone help?? This is my HTML and Javascript files (I am using some JQuery so you will have to link with the latest version if you want to run this).
<!DOCTYPE html>
<html>
<head>
<title>Mobile Signals</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="NetworkStats.js"></script>
</head>
<body>
<form id="postcodeForm">
Enter postcodes separated by commas<br>
<input type="text" id="postcodes" name="postcodes">
</br></br>
<input type="submit" value="Submit" id="submitButton">
</form>
<div id="theDiv">
</div>
<div id ="secondDiv"> </div>
<table id="theTable" border="1">
</table>
And Javascript
$( document ).ready(function() {
document.getElementById('submitButton').addEventListener('click', function() {
var input = $('#postcodeForm').serializeArray();
var postcodeString = input[0]["value"];
var output = postcodeString.split(",");
var postcodeString = "";
// check each postcode to see if there is any false postcodes
for (var postcode in output) {
var newPostcode = checkPostCode(output[postcode]);
if (newPostcode) {
postcodeString += " true ";
} else {
postcodeString += " false ";
}
}
if (postcodeString.indexOf("false") >= 0) {
// string contains a false so output an error message
window.alert("Sorry but you seem to have entered an incorrect postcode.")
} else {
// all the postcodes are correct, proceed to perform operations on them
processPostcodesOnServer(output);
}
}, false);
function processPostcodesOnServer(output) {
var apiKey = "c590c63f5b3818271a87a3e89fa215ae";
var distance = 10;
var tableNumber = 0;
//var output = ["WR141NE"];
for (var postcode in output) {
strippedPostcode = output[postcode].replace(/ /g,'');
getLatAndLong(strippedPostcode);
}
function googleCallback(latitude, longitude, postcode) {
contactServer(latitude, longitude, postcode);
}
/* Function to contact google and convert the postcode to lat long */
function getLatAndLong(postcode) {
var latitude;
var longitude;
var googleXmlHttp = new XMLHttpRequest();
var googleUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="+ postcode + "&sensor=false";
googleXmlHttp.onreadystatechange = function() {
if (googleXmlHttp.readyState == 4 && googleXmlHttp.status == 200) {
var latLong = JSON.parse(googleXmlHttp.responseText);
latitude = latLong.results[0].geometry.location.lat;
longitude = latLong.results[0].geometry.location.lng;
googleCallback(latitude, longitude, postcode);
}
}
googleXmlHttp.open("GET", googleUrl, true);
googleXmlHttp.send();
}
function contactServer(latitude, longitude, postcode) {
var xmlhttp = new XMLHttpRequest();
var networkStatsUrl = "http://api.opensignal.com/v2/networkstats.json?lat="+latitude+"&lng="+longitude+"&distance=" + distance + "&apikey=" + apiKey;
/*
Functions to contact server and read JSON response back for NetworkStats
*/
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
sortTableData(myArr, postcode);
//displayData(myArr);
}
}
xmlhttp.open("GET", networkStatsUrl, true);
xmlhttp.send();
var functionCount = -1;
function sortTableData(arr, postcode) {
tableNumber++;
$("body").append("</br>" + postcode + "</br>");
theTable = "<table id='table"+ tableNumber + "' border='1'> </table>"
$("body").append(theTable);
var column1 = new Array();
var column2 = new Array();
var column3 = new Array();
var column4 = new Array();
var column5 = new Array();
var column6 = new Array();
var column7 = new Array();
//var output = '<table border="1">';
//var output = "";
for (var obj in arr) {
// find all the networks
if ((typeof arr[obj] === 'object') && (obj == "networkRank")) {
var networks = new Object();
networks = arr[obj];
var allNetworkKeys = Object.keys(networks);
//console.log(allNetworkKeys);
var networksArray = new Array();
$.each(networks, function(networkKey, networkValue){
//Do something with your key and value.
column1.push(networkKey);
if (networkKey.substring(0, 7) == "network") {
$.each(networkValue, function(networkTypeKey, networkTypeValue){
if (networkTypeKey == "type2G") {
column2.push('');
column3.push(networkTypeKey);
for (var variable in networkTypeValue) {
column2.push(variable);
column3.push(networkTypeValue[variable]);
}
} else if (networkTypeKey == "type3G") {
column4.push('');
column5.push(networkTypeKey);
for (var variable in networkTypeValue) {
column4.push(variable);
column5.push(networkTypeValue[variable]);
}
} else if (networkTypeKey == "type4G") {
column6.push('');
column7.push(networkTypeKey);
for (var variable in networkTypeValue) {
column6.push(variable);
column7.push(networkTypeValue[variable]);
}
}
});
//console.log(column1);
}
//console.log(column1, column2, column3, column4);
displayTable(column1, column2, column3, column4, column5, column6, column7);
column1 = []; column2 = []; column3 = []; column4 = []; column5 = []; column6 = []; column7 = [];
});
}
}
}
var counter = 0;
function displayTable(column1, column2, column3, column4, column5, column6, column7) {
var output = ""
//console.log(counter);
counter++;
var column1Length = column1.length;
var column2Length = column2.length;
var column3Length = column3.length;
var column4Length = column4.length;
var column5Length = column5.length;
var column6Length = column6.length;
var column7Length = column7.length;
var highestNumber = Math.max(column1Length, column2Length, column3Length, column4Length, column5Length, column6Length, column7Length);
for (var i=0; i<highestNumber; i++) {
var column1Reference = column1[i];
var column2Reference = column2[i];
var column3Reference = column3[i];
var column4Reference = column4[i];
var column5Reference = column5[i];
var column6Reference = column6[i];
var column7Reference = column7[i];
if (column1Reference === void 0) {
column1Reference = " "
}
if (column2Reference === void 0) {
column2Reference = " "
}
if (column3Reference === void 0) {
column3Reference = " "
}
if (column4Reference === void 0) {
column4Reference = " "
}
if (column5Reference === void 0) {
column5Reference = " "
}
if (column6Reference === void 0) {
column6Reference = " "
}
if (column7Reference === void 0) {
column7Reference = " "
}
output += "<tr>";
output += "<td>" + column1Reference + "</td>";
output += "<td>" + column2Reference + "</td>";
output += "<td>" + column3Reference + "</td>";
output += "<td>" + column4Reference + "</td>";
output += "<td>" + column5Reference + "</td>";
output += "<td>" + column6Reference + "</td>";
output += "<td>" + column7Reference + "</td>";
output += "</tr>";
}
//output += "</table>";
//var table = document.getElementById('theTable');
//console.log(output);
//oldOutput = table.innerHTML;
//table.innerHTML = oldOutput + output;
$("#table" +tableNumber).append(output);
console.log(output);
}
}
}
});
Alright, I got it working.
The table would actually be displayed, if only submitting the form wouldn't reload the page.
There are two ways around this:
Change your click handler to a submit handler and cancel the event!
Replace
document.getElementById('submitButton').addEventListener('click', function() {
// ...
}, false);
by
document.getElementById('postcodeForm').addEventListener('submit', function(event) {
event.preventDefault();
// ...
}, false);
Remove the form:
That would be as simple as removing <form id="postcodeForm"> and </form> from your HTML code, but since you use $('#postcodeForm') in JS, you're gonna have to change
var input = $('#postcodeForm').serializeArray();
var postcodeString = input[0]["value"];
var output = postcodeString.split(",");
into
var output = document.getElementById('postcodes').value.split(",");
to make it work.
(Inlining postcodeString is not actually necessary, but I suggest it, see below.)
If you go with this option, I suggest also removing the name attribute from #postcodes, simply because it serves no purpose.
But regardless of which option you choose, you should fix all those </br>s: It's <br> in HTML 5 (and it was <br/> in HTML 4, but never </br>).
(And don't forget those in your JS!)
And what is the googleCallback function good for, if it only passes its arguments to a function with the exact same list of parameters? Why not use contactServer directly?
And this code is really inefficient:
var postcodeString = "";
// check each postcode to see if there is any false postcodes
for(var postcode in output)
{
var newPostcode = checkPostCode(output[postcode]);
if(newPostcode)
{
postcodeString += " true ";
}
else
{
postcodeString += " false ";
}
}
if(postcodeString.indexOf("false") >= 0)
{
// string contains a false so output an error message
window.alert("Sorry but you seem to have entered an incorrect postcode.")
}
else
{
// all the postcodes are correct, proceed to perform operations on them
processPostcodesOnServer(output);
}
I mean, strings, really? Consider:
// check each postcode to see if there is any invalid postcodes
for(var postcode in output)
{
if(checkPostCode(output[postcode]) === false)
{
// current postcode is invalid so output an error message and return
window.alert("Sorry but you seem to have entered an incorrect postcode.");
return;
}
// at this point, all the postcodes are valid, proceed to perform operations on them
processPostcodesOnServer(output);
Also, you use a lot of variables only exactly once, resulting in quite an overhead.
For example, this:
var column1Length = column1.length;
var column2Length = column2.length;
var column3Length = column3.length;
var column4Length = column4.length;
var column5Length = column5.length;
var column6Length = column6.length;
var column7Length = column7.length;
var highestNumber = Math.max(column1Length, column2Length, column3Length, column4Length, column5Length, column6Length, column7Length);
Which could be shortened to this:
var highestNumber = Math.max(column1.length, column2.length, column3.length, column4.length, column5.length, column6.length, column7.length);
Sure this makes the line a little longer, but for 7 additional characters you can save 7 entire lines!
Or, your displayTable function could really be shortened to this:
function displayTable()
{
var output = '';
var highestNumber = Math.max(arguments[0].length, arguments[1].length, arguments[2].length, arguments[3].length, arguments[4].length, arguments[5].length, arguments[6].length);
for(var i = 0; i < highestNumber; i++)
{
output += '<tr>';
for(var j = 0; j < 7; j++)
{
output += '<td>' + arguments[j][i] + '</td>';
}
output += '</tr>';
}
$('#table' + tableNumber).append(output);
}
Then, you have a lot of {1} in your RegEx - why? [0-9]{1} is equal to [0-9] (or \d, but with that be careful to escape \ if using it in strings).
And finally, I suggest you run your code through JSHint or something similar to get rid of inconsistencies (be careful with JSLint though, that one has really aggressive and unreasonable conventions).
You have var postcodeString twice.
var keyword should only be used once per scope.

autoincrement id in javascript variable

didn't really succes with assigning values to new ids in my while(row) statement:
Here is an easy example, hope you understand what I want to do. Thanks
<?php...
$id=0;
while(rows = mysql_fetch_data){
$id = $id + 1;
$teamname = rows['team'];
?>
<script>
var team = '<?php echo $teamname; ?>';
var id = 'id_<?php echo $id; ?>';
//Here I want to save the teamnames as javascript variable "id_1", "id_2" etc, which I can use outside the while statement.
//For each row id = id_1, id_2, id_3, id_4.
//I want to make id_1 a variable which outputs teamname
//So that
//var id_1 = team; //team 1
//var id_2 = team; //team 2
<?php
}
?>
var id_1;
var id_2;
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
I would recommend using an array rather than individual variables, as you have a list of team names:
<?php
$teamnames = [];
while(rows = mysql_fetch_data){
$teamnames[] = rows['team'];
}
?>
<script>
var teamnames = <?php echo json_encode($teamnames); ?>;
</script>
Then you end up with a client-side JavaScript array of team names. While you could then output them with document.write, there's probably a better option.
But here's your document.write updated to use the array:
var n;
for (n = 0; n < teamnames.length; ++n)
{
// Note: There's almost certainly a better choice than `document.write`
document.write("Teamname " + (n + 1) + " = " + teamnames[n] + "</br>");
}
Replace your code with the following and it should give you the output that you're after...
<script>
<?php
//...
$id_counter = 1; //Initialise counter
while($row = mysql_fetch_assoc()){
echo 'var id_'.$id_counter.' = "'.$rows['team'].'";'; //Echo row in the format: var id_X = "team_name";
$id_counter++; //Increment the counter
}
?>
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>

Assigning user input to object with variable in its index

I am trying to using the JS to take user input and modify certain object attributes based on the user's input. I am storing the object's index in the select's alt attribute in order to use that to update the correct object. I'm getting an error: element[Payment_Format_name] is undefined
The WF.php file takes data from a CSV and formats it into a mulch-dimensional object.
$(document).ready(function() {
$.getJSON('WF.php', function(data) {
var newDiv, NewDiv2, NewDiv3,InvoiceInfo, count, DeliveryMethod, PaymentFormat, Payment_Format_id, Payment_Format_name;
count = 0;
$.each(data, function(index, element) {
count = count + 1;
//document.write (count);
newDiv = $('<div/>').addClass('row').appendTo('#showdata');
newDiv3 = $('<div/>').addClass('hd').appendTo(newDiv);
$('<div class="hd_field">' + element['PmtRec']['RcvrParty']['Name']['Name1'] + '</div>').appendTo(newDiv3);
if (element['PmtRec']['PmtMethod'] === 'CHK'){
$('<div class="hd_field">Delivery Method: <select alt="Delivery_Method" " id="Delivery' + count +'" class="Delivery_Method"><option value="100" selected="selected">US Mail</option><option value="300">Foreign Mail</option><option value="J00">Certified Mail with Return Receipt</option></select><div id="Selected_Method' + count +'"></div></div>').appendTo(newDiv3);
}
else if (element['PmtRec']['PmtMethod'] === 'DAC') {
$('<div class="hd_field">Payment Format: <select alt="'+index +'" id="Payment_' + count +'" class="Payment_Format"><option value="CTX" selected="selected">Company to Company</option><option value="PPD">Company to Person</option></select><div id="Selected_Format'+count+'"></div></div>').appendTo(newDiv3);
}
$('<div class="hd_field">' + 'Total: ' + element['PmtRec']['CurAmt'] + '</div>').appendTo(newDiv3);
InvoiceInfo = element['PmtRec']['PmtDetail']['InvoiceInfo'];
$.each(InvoiceInfo, function(index, element) {
newDiv2 = $('<div/>').addClass('sub_row').appendTo(newDiv);
$('<div class="field">' + element['InvoiceNum'] + '</div>').appendTo(newDiv2);
$('<div class="field">' + element['NetCurAmt'] + '</div>').appendTo(newDiv2);
});
$('select.Payment_Format').change(function(){
Payment_Format_id = ($(this).attr('id').match(/[\d]+$/));
Payment_Format_name = ($(this).attr('alt'));
//alert(Payment_Format_name);
PaymentFormat = ($(this).val());
element[Payment_Format_name] = Payment_Format_name;
element[Payment_Format_name]['PmtRec']['PmtFormat'] = PaymentFormat;
$('#Selected_Format' + Payment_Format_id).text('Selected Format: ' + element[Payment_Format] );
});
});
console.log(data);
});
});
PHP (this is a snippet, I'm actually creating a lot more elements here)
if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$cardCodes = array();
$payments = array();
$details = array ();
while ($row = fgetcsv($handle, 1024, ",")) {
$cardCodes[] = array_combine($headers, $row);
}
$prevCode = '';
foreach ($cardCodes as $key => $value) {
$payments[$value['CardCode']]['PmtRec']['PmtCrDr'] = 'C';
$payments[$value['CardCode']]['PmtRec']['PmtFormat'] = 'CTX';
fclose($handle);
echo json_encode($payments)
Ok, so for starters,
$('select.Payment_Format').change(function(){
Payment_Format_id = ($(this).attr('id').match(/[\d]+$/));
Payment_Format_name = ($(this).attr('alt'));
PaymentFormat = ($(this).val());
element[Payment_Format_name] = Payment_Format_name;
element[Payment_Format_name]['PmtRec']['PmtFormat'] = PaymentFormat;
$('#Selected_Format' + Payment_Format_id).text('Selected Format: ' + element[Payment_Format] );
});
});
is not what you want - this function is reassigned to the change event of the 'select.Payment_Fomat' element for each iteration of $.each(data, function(index, element). The event listener should be added outside the $.each function, inside the $.getJson call and it needs to loop over the elements object, and try to find the correct data to update.
Apologies for the uselessness earlier, it was 5am and apparently I was slightly delusional.

Categories

Resources