Guest User

Untitled

a guest
May 30th, 2017
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ===========================================================================
  2. // ===========================================================================
  3. // CSV import
  4. // ===========================================================================
  5. // ===========================================================================
  6.  
  7. $(document).on('knack-scene-render.scene_XXX', function(event, view, record) {
  8.  
  9. //Import progress window functions - a super super ugly status display window
  10.   $("<table id='statusOverlay'><tbody><tr><td><b> Import progress Window </b></td></tr></tbody></table>").css({
  11.         "position": "fixed",
  12.         "top": "20%",
  13.         "left": "60%",
  14.         "width": "40%",
  15.         "height": "90%",
  16.         "background-color": "rgba(255,255,0,.7)",
  17.         "z-index": 10000,
  18.         "vertical-align": "top",
  19.         "text-align": "right",
  20.         "color": "#000",
  21.         "font-size": "10px",
  22.     }).appendTo("#kn-scene_344");
  23.  
  24.  
  25. function updateStatusInfo(myText){ //a function that updates the table display thing above
  26.     $("#statusOverlay > tbody > tr > td").append("<br />"+myText);
  27. };
  28.  
  29. //In my example, I had to link all imported records to the currently open "Projects" details page:
  30.   var filetext
  31.   var knackProjectID //the knack record identifier for this page's project
  32.  
  33.   //this is a "details" view from which I am extracting the unique front-facing project code, in order to look it up and get the knack back-end record ID
  34.   var projectCode = $("#view_831 > div.kn-details-column.first > div > div > table > tbody > tr.field_70 > td > span").text()
  35.  
  36.   console.log(projectCode);
  37.  
  38.   //All of our projects have different donors too. Budgetlines are connected to a project and to a donor. Projects and budgetlines are not connected directly.
  39.   //However, I can still make a details view to show all the donors associated with all the budget lines associated with the projects.
  40.   //I had to be sure the user didn't try to import a new donor, so this variable will help keep track of that:
  41.   var listOfDonors = [[],[]];
  42.   var currentProjectCurrencyID = ""
  43.   var x = {} //global counter
  44.   var existingBudgetLines //all existing budget lines
  45.   var scenarios
  46.   var initialCurrencyConversionRate //divide by this value to convert from donor currency to USD
  47.   var PPcategories
  48.  
  49.   updateStatusInfo("Looking up project record");
  50.  
  51.   // api to get the project record ID from the project code
  52.               var api_url = 'https://api.knack.com/v1/scenes/scene_186/views/view_889/records' //Projects table
  53.               userToken = Knack.getUserToken()
  54.               // preparing filters
  55.               var filters = [
  56.                 {
  57.                   field: 'field_70',
  58.                   operator: 'is',
  59.                   value: projectCode //find this Project Code record
  60.                 }
  61.               ]
  62.                
  63.               // add to URL
  64.               api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));
  65.        
  66.             Knack.showSpinner();
  67.             $.ajax({
  68.               url: api_url
  69.             , type: 'GET'
  70.             , headers: {
  71.                         'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
  72.                         , "X-Knack-REST-API-KEY": 'knack'
  73.                       , "Authorization": userToken //userToken is a public variable I set on each page load
  74.                         }
  75.                 , success: function(data) {                         //once you successflly get the record
  76.                   console.log(data)
  77.                   if (data.records.length != 1) {
  78.                       alert("Fatal error! Searched for project code " + projectCode + "which should be unique (1 result). Actually got " + data.length + "results. Is there a duplicate project code?!")
  79.                   } else {
  80.                         knackProjectID = data.records["0"].id
  81.                       currentProjectCurrencyID = data.records["0"].field_922_raw["0"].id //Projects can be in different currencies, so are connected to currencies object.
  82.                       console.log("Current project currency ID:") //the API call returns the connection ID (not field text) of the currencies.
  83.                       console.log(currentProjectCurrencyID);
  84.                       initialCurrencyConversionRate = data.records["0"].field_932_raw; //I have to convert these rates to USD as well, though
  85.                       console.log("initial Currency Conversion Rate:")
  86.                       console.log(initialCurrencyConversionRate)
  87.                       if (initialCurrencyConversionRate == "" || initialCurrencyConversionRate == 0){ //if not entered, assume 1
  88.                          updateStatusInfo("<b> No initial currency conversion rate set. Assuming donor contract currency is USD. </b>");
  89.                          initialCurrencyConversionRate = 1
  90.                          alert("No initial currency conversion rate has been set for this project. To work out default procurement scenarios, import will assume donor contract currency is USD. If this is incorrect, please first go back to the previous page and specify the donor contract currency.")
  91.                       }
  92.                       console.log("Knack Project ID:")
  93.                       console.log(knackProjectID);
  94.                         findExistingBudgetLines();
  95.                         updateStatusInfo("Retrieved project record.");  
  96.                   }
  97.  
  98.                 }
  99.                 , error: function (request, status, error) {
  100.                         handleAjaxError(request, status, error);
  101.                         }
  102.             });
  103.            
  104.            
  105.            
  106.     function findExistingBudgetLines(){
  107.        
  108.         var budgetLinesFromDetailsView = $("#view_831 > div.kn-details-column.first > div > div > table > tbody > tr.field_82 > td > span").text()  //this is a details view showing all budget lines
  109.         existingBudgetLines = budgetLinesFromDetailsView.split(',').map(function(item) { //function take off whitespace at start/end and split by , character
  110.             return item.trim();
  111.         });
  112.         console.log("Existing budget lines:")
  113.         console.log(existingBudgetLines);
  114.        
  115.         if (existingBudgetLines.length > 1) { // a few friendly notifications
  116.             updateStatusInfo("Some budget lines have already been entered for this project. These will be skipped during the import process.")
  117.         } else if (existingBudgetLines.length == 1 && existingBudgetLines[0] != "ACT") {
  118.             updateStatusInfo("There is already a budget line added to this project (other than the default 'ACT' line). Please ensure the CSV file you want to upload does not have duplicates of lines already on this system.")
  119.         } else {
  120.             updateStatusInfo("Done.");
  121.  
  122.         }
  123.         updateStatusInfo("Looking up Procurement Scenario Limits"); //we have to set a "default procurement scenario" field based on the value of the line, in USD
  124.         lookupProcurementScenarioLimits();
  125.     }
  126.  
  127.     function lookupProcurementScenarioLimits(){  //looks up procurement scenario limits. e.g < 200USD = scenario "A" etc
  128.           // api
  129.               var api_url = 'https://api.knack.com/v1/scenes/scene_186/views/view_987/records?sort_field=field_899&sort_order=asc' //Procurement Limits table  
  130.               userToken = Knack.getUserToken();
  131.             Knack.showSpinner();
  132.             $.ajax({
  133.               url: api_url
  134.             , type: 'GET'
  135.             , headers: {
  136.                         'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
  137.                         , "X-Knack-REST-API-KEY": 'knack'
  138.                       , "Authorization": userToken
  139.                         }
  140.                 , success: function(data) {                         //once you successflly get the record  
  141.                  scenarios = data //set variable
  142.                  console.log("Scenarios:")
  143.                  console.log(scenarios);
  144.                  addFileBox();
  145.                 }
  146.                 , error: function (request, status, error) {
  147.                         handleAjaxError(request, status, error);
  148.                         }
  149.             });
  150.     }
  151.    
  152.  
  153.                
  154. function addFileBox(){
  155.    
  156.     $('#view_831').append('<br><p> Please select a CSV file for import: </p>');
  157.     $('#view_831').append('<input type="file" id="myFileBox" name="file" enctype="multipart/form-data" />'); //add an input box
  158.     Knack.hideSpinner()
  159.    
  160.     document.getElementById('myFileBox').addEventListener('change', function(e) { //once a file has been selected, load it up
  161.             console.log("Called fileChanged function");
  162.             var file = myFileBox.files[0];
  163.             console.log(file);
  164.             var textType = /.+(\.csv)$/ ;
  165.             console.log(file.type)
  166.             $("#myImportButton").remove();
  167.  
  168.             if (file.name.match(textType)) {  //check for .csv file extension
  169.                 var reader = new FileReader();
  170.                
  171.              
  172.                 reader.readAsText(file);    //load/read this as a text file
  173.                 reader.onload = function(e) { //once loaded, do this
  174.                     fileText = reader.result;      
  175.                     processData(fileText);
  176.                     console.log("Currency conversion rate as of addFileBox function:")
  177.                     console.log(initialCurrencyConversionRate)
  178.                 }  
  179.                
  180.             } else {
  181.                 alert("File not supported! Only files with a .csv extension can be uploaded here.")
  182.             }
  183.         });
  184. };
  185.  // Here I display the CSV file to the user but with my own "custom" headings, to make sure everything is "matching up". Then I prompt the user to continue.
  186.  function processData(fileText) {
  187.  
  188.      Knack.showSpinner();
  189.      $('#view_831 > table.table-data-omset').remove()  //this gets rid of the display table, in the case that the user changed the file.
  190.     var allTextLines = fileText.split(/\r\n|\n/); //split the CSV file in to rows
  191.     var headers = allTextLines[0].split(','); //split again by comma
  192.     //NOTE: THIS WORKS FOR LEGACY CSV FILES WHERE THE COMMAS IS REALLY THE DELIMITER
  193.     //EXCEL CSV FILES TAKE A DIFFERENT FORMAT, each row as follows:
  194.     //"Field1","Field2","Field3"
  195.     //Modify the above code to suit. I was importing from a program which did just strictly delimit by comma only.
  196.    
  197.    console.log("Headers:")
  198.    console.log(headers)
  199.    
  200.     var lines = [];
  201.  
  202.     for (var i=1; i<allTextLines.length; i++) { //FOR EACH ROW
  203.         var data = allTextLines[i].split(',');  //data = an individual row
  204.       console.log("Data row extracted:")
  205.       console.log(data);
  206.         if (data.length == headers.length) { //If the number of fields extracted was equal to the number of header fields (OK)
  207.             var tarr = [];
  208.             for (var j=0; j<headers.length; j++) { //FOR EACH COLUMN
  209.                 tarr.push(data[j]); //Add column to second dimension of data array data[j,0], data[j,1] etc...
  210.             }
  211.             lines.push(tarr); //then push that row on to the lines object
  212.         } else { //otherwise, there was a comma within the data itself - show a warning and skip
  213.         if (data.length > 1)    {
  214.             var number = i +1;
  215.             alert("Please check row " + number + " carefully and ensure there is no comma (,) present in any of the CSV cells. Otherwise this row will not be imported.")
  216.             };
  217.         }
  218.     }
  219.     console.log(lines);
  220.     console.log(lines.length);
  221.     console.log(lines[0].length);
  222.    
  223.    
  224.    $('#view_831').append('<table class="table table-striped table-bordered table-data-omset"><tbody></tbody></table>') //draw a table
  225.    
  226.    var tableOmset = $('table.table-data-omset');
  227.    
  228.     var tbodyTableOmset = tableOmset.find('tbody');
  229.    
  230.     var trTableOmset = '';
  231.    
  232.     //add custom headers
  233.    
  234.     trTableOmset += '<tr>'  ;    
  235.     trTableOmset += '<td><h4>'+  " x " +'</h4></td>';
  236.        
  237.         for(var b=0; b<headers.length; b++){
  238.                  
  239.         if (b==0) {
  240.               trTableOmset += '<td><h4>'+ "Custom header 1" +'</h4></td>';
  241.           }
  242.          
  243.           else if (b==2){
  244.             trTableOmset += '<td><h4>'+ "DONOR CODE" +'</h4></td>';  
  245.           }      
  246.          
  247.           else if (b==3){
  248.             trTableOmset += '<td><h4>'+ "BUDGET LINE (LAST THREE LETTERS)" +'</h4></td>';  
  249.           }
  250.          
  251.           else if (b==6){
  252.             trTableOmset += '<td><h4>'+ "LINE DESCRIPTION" +'</h4></td>';  
  253.           }
  254.          
  255.           else if (b==10){
  256.             trTableOmset += '<td><h4>'+ "VALUE (donor currency)" +'</h4></td>';  
  257.           }
  258.           else {
  259.             trTableOmset += '<td> x </td>';    
  260.           }
  261.          
  262.         }
  263.        
  264.         trTableOmset += '</tr>' ;
  265.    
  266.     // add headers from CSV
  267.  
  268.         trTableOmset += '<tr>'  ;    
  269.         trTableOmset += '<td><b>'+ "1" +'</b></td>'; //number first column
  270.        
  271.         for(var b=0; b<headers.length; b++){ //add headers from CSV file
  272.          
  273.  
  274.          
  275.             if(headers[b] === null || headers[b].length > 40){
  276.                  headers[b]= 'x';
  277.             }
  278.          
  279.             trTableOmset += '<td><b>'+ headers[b] +'</b></td>';
  280.         }
  281.        
  282.         trTableOmset += '</tr>' ;
  283.    
  284.        
  285.    
  286.     //add data, row by row
  287.     for(var a=0; a<lines.length; a++){ //for each line of CSV
  288.         if (lines[a][3]!=""){ //Some of my CSV lines were "header" information and not actual data to import. In that case, column [3] was blank
  289.                                 // so, if blank, do this:
  290.             currentRow = a + 2 ; //row number (a indexes from 0, excel indexes rows from 1 and has a header)
  291.             trTableOmset += '<tr>'  ;    
  292.             trTableOmset += '<td><b>'+ currentRow +'</b></td>'; //label the row
  293.             for(var b=0; b<lines[0].length; b++){ // for each row
  294.              
  295.                 if(lines[a][b] === null || lines[a][b].length > 80){ //Some of my fields had very long text that I didn't need, so I replaced with X
  296.                      lines[a][b]= 'x';
  297.                 }
  298.              
  299.                 trTableOmset += '<td>'+ lines[a][b] +'</td>'; //print
  300.             }
  301.         trTableOmset += '</tr>' ;
  302.         } else { //if a[3] was just blank
  303.             currentRow = a + 2 ; //corresponding row of the excel spreadsheet
  304.             trTableOmset += '<tr>'  ;    
  305.             trTableOmset += '<td><b>'+ currentRow +'</b></td>';
  306.             trTableOmset += '<td> Row in CSV is header </td>'; //just add a message in that first cell
  307.             for(var b=1; b<lines[0].length; b++){
  308.  
  309.             lines[a][b]= '-'; //and a "-" character for the rest of the row
  310.          
  311.             trTableOmset += '<td>'+ lines[a][b] +'</td>';
  312.             }
  313.            
  314.            
  315.         }
  316.     }
  317.     tbodyTableOmset.append(trTableOmset);
  318.    
  319.     var donorField = 2 //One of the columns was my "donor" field. I need to check all donors in the CSV already exist, before importing.
  320.    
  321.     checkDonorCodesExist(lines, donorField)
  322.    
  323.     };
  324.    
  325.     function checkDonorCodesExist(lines, b) {
  326.         Knack.showSpinner();
  327.         var thisDonor;
  328.         x = 0
  329.             for (var a = 0; a<lines.length; a++){  //for each line
  330.                 thisDonor = lines[a][b]             //this is the donor (b is column id passed to this function, not a counter now)
  331.  
  332.                 if ($.inArray(thisDonor, listOfDonors[0],0) == -1 && thisDonor != "-"){  //if not already in list
  333.                     listOfDonors[0].push(thisDonor)                                     // add to list
  334.                     x++     //increment
  335.                 }
  336.        
  337.             }
  338.             console.log("List of donors:")
  339.             console.log(listOfDonors)
  340.             console.log(x)
  341.            
  342.             $('#view_831').append('<br> <input type="button" value="Looks good, add these lines to project" id="myImportButton"/>')      //add button
  343.             $('#myImportButton').hide(); //hide it
  344.    
  345.             for (a = 0; a<listOfDonors[0].length; a++) {   //for each donor in list
  346.                
  347.                 checkIfInList(listOfDonors[0][a], a)  //check if the donor is in the list... and add if not.
  348.                
  349.             }
  350.  
  351.            
  352.             Knack.hideSpinner();                                    //hide the "loading" spinny thing
  353.        
  354.  
  355.                
  356.  
  357.         function checkIfInList(donorCode, a){
  358.                 var A = {} //change A to object, so I can access this inside my AJAX
  359.                 A = a
  360.                 var donorCODE = {}; //use object to endure reference inside AJAX
  361.                 donorCODE = donorCode;
  362.                 // api
  363.                 var api_url = 'https://api.knack.com/v1/scenes/scene_186/views/view_988/records' //Donor List
  364.                    
  365.                 // preparing filters
  366.                 var filters = [
  367.                     {
  368.                       field: 'field_142',
  369.                       operator: 'is',
  370.                       value: donorCode //search for this donor code
  371.                     }
  372.                   ]
  373.                   console.log("Checking for donor code " + donorCode)
  374.                     // add to URL
  375.                     api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));
  376.                  
  377.                 $.ajax({
  378.                     url: api_url
  379.                   , type: "GET"
  380.                   , headers: {
  381.                         'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
  382.                         , "X-Knack-REST-API-KEY": 'knack'
  383.                       , "Authorization": userToken
  384.                     }
  385.                   , success: function(data) {
  386.                         console.log("Successful ajax call for donor code. Returned:")
  387.                         console.log(data)
  388.                         if (data.records.length == 0) { //if doesn't already exist
  389.                         var donorName = prompt("Donor code " + donorCODE + " is not in the database. Press OK to add now. Optionally, please enter the name of the donor here ('UNHCR', 'GIZ', etc).")
  390.                             if (donorName != null){ //if user didn't click cancel
  391.                                 addDonorCode(donorName, donorCODE, A);
  392.                                 Knack.showSpinner();
  393.                             }
  394.                         } else {
  395.                             listOfDonors[1][a] = data.records["0"].id //note the record ID of this donor
  396.                             console.log("List of donors:")
  397.                             console.log(listOfDonors);
  398.                             x--
  399.                             showButton(listOfDonors[0][a])
  400.                            
  401.                         }
  402.                     }
  403.                         , error: function (request, status, error) {
  404.                         handleAjaxError(request, status, error); //custom error function
  405.                         }
  406.                     })
  407.             }
  408.        
  409.        
  410.     }
  411.    
  412. function addDonorCode(donorName, donorCode,A) {
  413.             var api_url = 'https://api.knack.com/v1/scenes/scene_391/views/view_989/records' //Donor create form
  414.             userToken = Knack.getUserToken();      
  415.             var dataToPost = ""
  416.                     dataToPost = {
  417.                     field_142: donorCode,
  418.                     field_641: donorName
  419.                     };
  420.                    
  421.     $.ajax({
  422.                     url: api_url
  423.                   , type: "POST"
  424.                   , headers: {
  425.                         'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
  426.                         , "X-Knack-REST-API-KEY": 'knack'
  427.                       , "Authorization": userToken
  428.                     }
  429.                   , data: dataToPost                                     
  430.                   , success: function(data) {
  431.                         console.log("Successful ajax post for creating donor. Returned:")
  432.                         console.log(data)
  433.                         x-- //increment x
  434.                         showButton(data.record.field_142);
  435.                         listOfDonors[1][A] = data.record.id //record the record ID from this connected donor object (in position [1,x])
  436.                         Knack.hideSpinner();
  437.                     }
  438.                     , error: function (request, status, error) {
  439.                                                 handleAjaxError(request, status, error);
  440.                         Knack.hideSpinner();
  441.                         }
  442.                     })
  443.        
  444.        
  445. };
  446.    
  447. function showButton(donorCode){
  448.     if (x==0){ //if all donors have been imported/dealt with (x is global var somewhere)
  449.         $("#myImportButton").show()
  450.         updateStatusInfo("Checking for donor " + donorCode + ".")
  451.         updateStatusInfo("Done checking donors, click button to continue.")
  452.     } else {
  453.         updateStatusInfo("Checking for " + donorCode + ".")
  454.     }
  455. }
  456.        
  457. // ==========================================
  458. // Main import code
  459. // ==========================================
  460.  
  461.     $("#view_831").on('click',"#myImportButton",function(){
  462.                 console.log("Starting import")
  463.                 Knack.showSpinner();   
  464.                 updateStatusInfo("Starting import");
  465.  
  466.         var allTextLines = fileText.split(/\r\n|\n/); //split again etc
  467.         var headers = allTextLines[0].split(',');
  468.         var lines = [];
  469.  
  470.         for (var i=1; i<allTextLines.length; i++) {
  471.             var data = allTextLines[i].split(',');  //data = an individual row
  472.           console.log("Data row extracted:")
  473.  
  474.                 var tarr = [];
  475.                 for (var j=0; j<headers.length; j++) {
  476.                     tarr.push(data[j]);
  477.                 }
  478.                 lines.push(tarr);
  479.         }
  480.  
  481.         addBudgetLine1(lines, 0);
  482.      
  483.        
  484.        
  485.         //add data
  486.        
  487.         function addBudgetLine1(lines, a){
  488.         console.log("Called addBudgetLine1 function. a = " + a)
  489.         console.log ("Lines.length = " + lines.length)
  490.         console.log(lines)
  491.         if (a < lines.length){ //if not finished yet
  492.             console.log("BL is:")
  493.             console.log(lines[a][3]);
  494.             console.log("Line length:")
  495.             console.log(lines[a].length)
  496.             if (lines[a][3]!="" && typeof lines[a][3] != 'undefined'){ //if budgetline code is not blank and line is not blank
  497.             var message = "Importing line " + lines[a][3]
  498.             updateStatusInfo(message) //update my box thing
  499.                 var indexOfDonorID = $.inArray(lines[a][2], listOfDonors[0],0)      //search listOfDonors to find record ID            
  500.                 var donorID = listOfDonors[1][indexOfDonorID]
  501.                 var budgetLineCode = lines[a][3].substr(lines[a][3].length - 3) //last 3 digits
  502.  
  503.                 console.log(budgetLineCode)
  504.                     if ($.inArray(budgetLineCode,existingBudgetLines) == -1){ //if not already existing
  505.                         addBudgetLine2(budgetLineCode, lines[a][6],lines[a][10],donorID,a,lines);
  506.                     } else {
  507.                         updateStatusInfo(budgetLineCode + " is already imported. Skipping this row of the CSV file.")
  508.                         a++ //increment a
  509.                         addBudgetLine1(lines,a)
  510.                     }
  511.                        
  512.             } else {
  513.                 if (typeof lines[a][3] != 'undefined') {
  514.                     console.log("Skipped line for a = " + a)
  515.                     a++ //increment a
  516.                     addBudgetLine1(lines,a)
  517.                 } else {
  518.                     console.log("Looks like end of file!")
  519.                     a++ //increment a
  520.                     addBudgetLine1(lines,a)
  521.                 }
  522.                
  523.             }
  524.         } else {
  525.             alert("Finished.")
  526.             Knack.hideSpinner();
  527.         }
  528.                
  529.         };
  530.  
  531.            
  532.             //=====================
  533.             //POST/add budget line function
  534.             //=====================
  535.            
  536.             function addBudgetLine2(budgetLineCode, description, totalAmount, donorID,a,lines){ //last two parameters passed just to callback function1 later
  537.                 var api_url = 'https://api.knack.com/v1/scenes/scene_344/views/view_990/records' //"Add Budget Line" form
  538.                 var equivalentUSD = totalAmount / initialCurrencyConversionRate
  539.                 console.log("Total value (function addBudgetLine2):")
  540.                 console.log(totalAmount)
  541.                 console.log("Converstion rate:")
  542.                 console.log(initialCurrencyConversionRate)
  543.                
  544.                 var dataToPost = ""
  545.                         dataToPost = {
  546.                         field_927: description,
  547.                         field_178: knackProjectID,
  548.                         field_654: totalAmount, //in donor currency
  549.                         field_179: donorID,
  550.                         field_82: budgetLineCode,
  551.                         field_656: equivalentUSD,
  552.                         field_958: currentProjectCurrencyID,
  553.                         };
  554.                        
  555.                    
  556.                    
  557.                         console.log("Equivalent USD")
  558.                         console.log(equivalentUSD)
  559.  
  560.                         for (var k=0; k<scenarios.records.length; k++) {                           
  561.                                 if (Number(equivalentUSD) < Number(scenarios.records[k].field_899_raw)){ //find the scenario limit. If USD value is less than max value for the current scenario...
  562.                                     dataToPost['field_657'] = scenarios.records[k].field_898; //set scenario field
  563.                                     dataToPost['field_658'] = scenarios.records[k].field_900; //and an additional related field
  564.                                     break;
  565.                                 }  
  566.    
  567.  
  568.                             }
  569.                             console.log("Chosen scenario:")
  570.                             console.log(dataToPost['field_657'])
  571.         $.ajax({
  572.                         url: api_url
  573.                       , type: "POST"
  574.                       , headers: {
  575.                             'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
  576.                             , "X-Knack-REST-API-KEY": 'knack'
  577.                           , "Authorization": userToken
  578.                           ,"Content-Type":"application/json"
  579.                         }
  580.                       , data: JSON.stringify(dataToPost)                                     
  581.                       , success: function(data) {
  582.                             console.log("Successful added line:")
  583.                             console.log(data)
  584.                             a++ //increment a
  585.                             addBudgetLine1(lines,a) //and go back and repeat
  586.                         }
  587.                         , error: function (request, status, error) {
  588.                             handleAjaxError(request, status, error);
  589.                             Knack.hideSpinner();
  590.                             }
  591.                         })
  592.            
  593.            
  594.         };
  595.                
  596.                
  597.            
  598.        
  599.     });
  600. });
Advertisement
Add Comment
Please, Sign In to add comment