find all label and product in json python - json

I'm trying to find all label and product in text/javascript, but I don't have any idea to how do it. I'm trying to parse label, id and products.
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});

It's possible to do that less elegantly but without regex - just a series of splits and clean ups:
import json
code = [your script above]
code2 = html.replace('½','').split('":"Taglia","options":[{')[1].split('}]}},"template"')[0].split('},{')
for i in range(len(code2)):
data = json.loads('{'+code2[i]+'}')
print(data['id'],data['label'])
Output:
730 36
731 37
732 38
733 38
etc.

You can regex out javascript object and pass to json then parse out info
import re
import json
#html = response.content from requests
html = '''
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});'''
p = re.compile(r'Product\.Config\((.*?)\)', re.DOTALL)
data = json.loads(p.findall(html)[0])
for attribute in data['attributes']:
print('-----------------attribute--------------')
print('label = ' + data['attributes'][attribute]['label'], 'id = ' + data['attributes'][attribute]['id'])
print('-----------------options----------------')
for product in data['attributes'][attribute]['options']:
print('label = ' + product['label'], 'id = ' + product['id'], 'product = ' + product['products'][0])

Related

How to save to database by using ajax

I have a code which is works fine, but the data cannot save to the database. I want to insert cost, currency_rate, profit_rate and pprice to database through Ajax. Here are the code of javascript and update.php, I have tried to modify the code to save in my Mysql server, but it didn't success. Can someone help with this?
javascript
$(".profitRate").change(function() {
var myArray = [];
//find closest table->next table
var elem = $(this).closest('table').next('table');
var action = elem.find('tr').data('action');
console.log(action)
var profitRate = Number($("#profitRate").val());
//looping
elem.find('tr').each(function() {
//get cost
var cost = $(this).find('input[name=cost]').val();
//get curency rate
var currecy_rate = $(this).find('select[name=currency_rate]').val();
//calculate profit
var profit_total = Math.round(cost * profitRate * currecy_rate)
$(this).find('input[name=pprice]').val(profit_total)
//add to json object
auto_array = {};
auto_array["cost"] = cost;
auto_array["currecy_rate"] = currecy_rate;
auto_array["pprice"] = profit_total;
myArray.push(auto_array) //push to array
});
console.log(myArray)
form_data = elem.find('tr').data('action');
$.ajax({
data: {
action: action,
form_data: form_data,
},
url: 'update.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
}
}
});
})
update.php
<?php
if ($_POST['action'] == 'update_price') {
parse_str($_POST['form_data'], $my_form_data);
$id = $my_form_data['id'];
$cost = $my_form_data['cost'];
$profit_rate = $my_form_data['profit_rate'];
$currency_rate = $my_form_data['currency_rate'];
$pprice = $my_form_data['pprice'];
$sql = $query = $finalquery = $sqlresult = '';
if ($cost){
$sql.="cost='$cost',";
}
if ($profit_rate){
$sql.="profit_rate='$profit_rate',";
}
if ($currency_rate){
$sql.="currency_rate='$currency_rate',";
}
if ($pprice){
$sql.="pprice='$pprice',";
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
}

Alexa (Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined')

My code is not working when I test it in Amazon Developer and I don't see anything wrong with my code. It says my response is invalid.
Here's the code I tried to run but failed(I ran one response but not the other):
var Alexa = require('alexa-sdk');
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
// alexa.dynamoDBTableName = 'YourTableName'; // creates new table for userid:session.attributes
alexa.registerHandlers(handlers);
alexa.execute();
};
var handlers = {
'LaunchRequest': function () {
this.emit('WelcomeIntent');
},
'WelcomeIntent': function () {
this.emit(':ask', 'Welcome to the guessing game! What difficulty would you like to play? Easy, Medium, or Hard?');
},
//------------------------------------------------------------------------------------------------------------------------------------------------
'DifficultyIntent': function (){
var difficulty = this.event.request.intent.slots.difficulty.value;
var range = 10; this.attributes['RandomNumberEnd'] = range;
if (difficulty === 'easy')
{ range = 10;
this.emit[':ask Your range is 1 - ' + range]
}
else if (difficulty === 'medium')
{ range = 100;
this.emit[':ask Your range is 1 - ' + range]
}
else (difficulty === 'hard');
{ range = 1000;
this.emit[':ask Your range is 1 - ' + range]
}
var randomNumber = Math.floor((Math.random()*range)+1);
var rightAnswer = this.attributes['rightAnswer'] = rightAnswer;
}, //check the user's guess with the right answer
'UserGuessIntent': function (){
var guess = this.event.request.intent.slots.guess.value;
this.attributes['guess'] = guess;
this.emit('CheckIntent'); },
'CheckIntent': function (){
var guess = this.attributes['guess'];
this.attributes['rightAnswer'] = randomNumber;
if(guess < rightAnswer){
this.emit(':ask', 'Try Again! Guess higher!');
}
else if(guess > rightAnswer)
{this.emit(':ask', 'Try Again! Guess lower!');
}
else{
this.emit(':tell', 'You are correct! Congratulations!');
}
},
'QuitIntent': function(){
var stop = this.event.request.intent.slots.stop.value;
this.emit('AMAZON.StopIntent');
},
'AMAZON.StopIntent' : function(){
var rightAnswer = this.attributes['rightAnswer'];
this.emit(':tell', 'The right answer is ' + rightAnswer + '. Goodbye!');
}
};

how to convert into a json object

i have a file named 'funcJson.json'
whose content are as follows:
{
"fid":{
"processDate":function ()
{
data=MainMasterarr;
for(var i=0;i<data.length;i++)
{
data[i]['_id'] =data[i]['_id'].substring(0,8);
var mongoId = data[i]["_id"];
var dateObject = new Date( mongoId );
dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );
var date = dateObject.getDate();
var month = dateObject.getMonth()+1;
var year = dateObject.getFullYear().toString();
var yearSub = year.substring(2,4);
if(month<10)
month='0'+ month;
if (date<10)
date='0'+ date;
var dateString = month+'/'+date+'/'+yearSub;
data[i]['fid'] = dateString;
}
} ,
"consoleDate":function ()
{
data=MainMasterarr;
console.log(data[0]['fid']);
}
}
}
now i trying to read this file and convert the file content to json object.
when i equate the above json to a variable.it works like json object but now when i m trying to read it from a file it throws error.
my client side code is below:
function fetchFileData(fn,callback)
{
var fileName='funcJson.json';
var request = new goog.net.XhrIo();
var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
"fileN":fileName,
}));
goog.events.listen(request, "complete", function()
{
if (request.isSuccess())
{
if(request.getResponseText() == 'fails')
{
callback("error");
return;
} //if response fails
else
{
var response = request.getResponseJson();
fileData=response;
console.log(fileData);
callback(response);
}//else
} //if request is success
});//listen event
request.send(fetchFileUrl, "POST", data);
//return fileData;
};
and server side code is as follows
function fetchFile(req,res,params)
{
var fs = require('fs');
//var configJson = {};
var fileName=params.fileN;
fs.readFile(fileName, 'utf8', function (err, data) {
if (err)console.log(err);
//console.log(data);
//configJson = JSON.parse(data);
res.writeHead(200, {
"Content-Type": "text/plain"
});//res.writeHead
res.write(data);
res.end();
});
}
If i take a normal json with functions in it give me result as object which i can instantiate to variable and use that variable as json object.but as i give function declaration in json file.it throws error.
plz guide
changed the json format and it worked
format is as follows:
{
"fid":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
},
"nloc":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
}
}

Export to CSV issue

Hi I am trying to export dynamic table in the form of csv file. I am facing two issue
Only the first page of the table is getting displayed in the exported file. As it is a dynamically filled table there can be multiple pages. I am allowing 10 items per page.
The file that is getting exported is not in csv format . It is in some default file format.
If somebody could help. Let me know if you need any other details:
Code:
function exportTableToCSV() {
var tab = $('#searchObjectTableTabs').tabs('getSelected');// selecting the table
var tabIndex = $('#searchObjectTableTabs').tabs('getTabIndex', tab);
var data;
var rows;
if (tabIndex == '0') // first index of the tab under which the table will be displayed
{
data = $('#dg').first(); //Only one table
rows = $('#dg').datagrid('getRows');
} else if (tabIndex == '1') // second index
{
data = $('#doc').first(); //Only one table
rows = $('#doc').datagrid('getRows');
}
var csvData = [];
var tmpArr = [];
var tmpStr = '';
data.find("tr").each(function () {
if ($(this).find("th").length) {
$(this).find("th").each(function () {
tmpStr = $(this).text().replace(/"/g, '""');
tmpArr.push('"' + tmpStr + '"');
});
csvData.push(tmpArr);
}
tmpArr = [];
$.each(exportArray, function (index, value) {
csvData.push(exportArray[index].ID + "," + exportArray[index].itemrev + "," + exportArray[index].type + "," + exportArray[index].status + "," + exportArray[index].desc + "," + exportArray[index].owner + "," + exportArray[index].ogrp);
});
csvData.push(tmpArr.join('\n'));
// printObject(tmpArr);
});
var output = csvData.join('\n');
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(output);
window.open(uri);
}
Please try this one:
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
Demo
Thanks for the answer. I have done some editing and now I am able to retrieve the csv file. However I am only getting the values for the first page. For ex: If I have 20 pages in my table grid. the export is happening only for the first page
Is it because of this part of the code: Can we have a different syntax
{
data = $('#dg').first(); //Only one table
rows = $('#dg').datagrid('getRows');
}
Full Code:
function exportTableToCSV(filename) {
var tab = $('#searchObjectTableTabs').tabs('getSelected');// selecting the table
var tabIndex = $('#searchObjectTableTabs').tabs('getTabIndex', tab);
var data;
var rows;
alert('inside');
if (tabIndex == '0') // first index of the tab under which the table will be displayed
{
data = $('#dg').first(); //Only one table
rows = $('#dg').datagrid('getRows');
} else if (tabIndex == '1') // second index
{
data = $('#doc').first(); //Only one table
rows = $('#doc').datagrid('getRows');
}
var csvData = [];
var tmpArr = [];
var tmpStr = '';
data.find("tr").each(function ()
{
if ($(this).find("th").length) {
$(this).find("th").each(function () {
tmpStr = $(this).text().replace(/"/g, '""');
tmpArr.push('"' + tmpStr + '"');
});
csvData.push(tmpArr);
}
tmpArr = [];
$.each(exportArray, function (index, value)
{
csvData.push(exportArray[index].type + "," + exportArray[index].status + "," + exportArray[index].ID + "," + exportArray[index].itemrev + "," + exportArray[index].desc + "," + exportArray[index].owner + "," + exportArray[index].ogrp);
});
csvData.push(tmpArr.join('\n'));
// printObject(tmpArr);
});
alert('before this');
var output = csvData.join('\n');
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(output);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
alert('done');
}
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this,['export.csv']);
});

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};