Users from Microsoft SQL Server to Moodle - javascript

I have to sync users from an existing Microsoft SQL Server to Moodle via the API.
I have done some batch uploading from a csv file like this:
insertMoodleGebruikersBatch(array: csvGebruiker[]) {
this.functionName = "core_user_create_users";
this.urlParameters = "";
for (let x = 0; x < array.length; x++) {
this.urlParameters +=
"&users[" + x + "][username]=" + array[x][0] +
"&users[" + x + "][password]=" + array[x][1] +
"&users[" + x + "][firstname]=" + array[x][2] +
"&users[" + x + "][lastname]=" + array[x][3] +
"&users[" + x + "][email]=" + array[x][4];
}
this.serverurl = this.baseDomain + "/webservice/rest/server.php" + "?wstoken=" + this.token + "&wsfunction=" + this.functionName;
this.fullurl = this.serverurl + this.urlParameters;
this.urlParameters = "";
return this.http.get("http://" + this.fullurl);
}
This is very ugly and slow. I have to think there is another way I can do this, like giving JSON data as a payload to Moodle.
But I can't find anything about this subject.
Any ideas how to improve my code?
Thanks in advance!

Related

How can I make this XMLHttpRequest for Leaflet more simple? Just vanilla JS

Can this be better? More simple?
My Steps:
Created a Google Doc Sheet -spread sheet
Exported as json
Build this ajax js script to make available to leaflet. js app.
https://jsfiddle.net/lukedohner/by80bvL7/
There maybe a more succinct way.
xhr.onload = function() {
console.log("onload + function");
if (xhr.status === 200) {
//sucessfull load of json
alert("Here is the data in a alert window " + xhr.responseText);
var respText = xhr.responseText;
xhrText = JSON.parse(respText); // convert it to an object
console.log(
"json data: xhrText.length >>>>>>>> " +
Object.keys(xhrText.mysheet).length
);
console.log(
"Object.keys(xhrText) >>>>>>>> " + Object.keys(xhrText)
);
var i = -1;
for (var mykey in xhrText.mysheet) {
//In case you want to check to see it there is a null value -property
if (xhrText.mysheet.hasOwnProperty(mykey)) {
i++;
window["card" + i] = mykey + " -> " + xhrText[mykey];
}
}
} else {
// not sucessfull load of json
alert("Request failed. Returned status of " + xhr.status);
}
createhooks();
};
};
var ch = {}; // create a var namespace
createhooks = function() {
var mysheetlenght = Object.keys(xhrText.mysheet).length;
for (var j = 0; j < mysheetlenght; j++) {
//console.log(" xhrText.title >>>>>>>> " + j + " " + xhrText.mysheet[j].title);
ch["title" + j] = xhrText.mysheet[j].title;
ch["subtitle" + j] = xhrText.mysheet[j].subtitle;
ch["copy" + j] = xhrText.mysheet[j].copy;
ch["imagename" + j] = xhrText.mysheet[j].imagename;
console.log("title" + j + " is " + ch["title" + j]);
console.log("subtitle" + j + " is " + ch["subtitle" + j]);
console.log("copy" + j + " is " + ch["copy" + j]);
console.log("imagename" + j + " is " + ch["imagename" + j]);
console.log("~~~~~ " + "~~~~~ ");
//create vars for addLElement function - Display it is the DOM
titleindex = "ch.title" + j;
addElement("Title " + j, ch["title" + j]);
subtitleindex = ["ch.subtitle" + j];
addElement("Subtitle " + j, ch["subtitle" + j]);
copyindex = ["ch.copy" + j];
addElement("Copy " + j, ch["copy" + j]);
imagenameindex = ["ch.imagename" + j];
addElement("Image Name " + j, ch["imagename" + j]);
addElement("~~~~~ ", "~~~~~");
}
ch_callback();
};
function ch_callback() { // Use ch.title1, ch.title1, ch.title1, ch.title1, ch.title1... in your add addElement function or in the Leaflet.js L.control.window method
console.log("callback " + ch.copy1);
}
Now I can use the var like this ch.copy1 in the leaflet L.control.window method. Not shown in fiddle example.

QtCreator intellisense missing when importing js files with Qt.include(...)

Qt Creator is a good editor, but sometimes it is very frustrating. The fact is that intellisense does not always work correctly.
Sample project would look`s like this:
//Test1.js file
function test1() {
console.log('hi from test1');
}
//Test2.js file
Qt.include('Test1.js');
function test2() {
console.log('hi from test2');
test1();
}
//Test.qml file
import QtQuick 1.1
import "Test2.js" as Test2
QtObject {
Component.onCompleted: {
Test2.test1(); //<--- intellisense missing here
Test2.test2();
}
}
The trouble:
The editor intellisense miss the test1 function included in imported Test2.js. The Qt.include is simple thing - just say qml compiler - hey, copy and paste this js file content here.
The questions is
Is any way to fix this QtCreator behavior?
Is QtCreator plugin model allow to add this behaviour to existing intellisense code? Or this should be fixed with patching QtCreator code base?
Quick and dirty patch.
Need to patch 2 files
source\qt-creator\src\libs\qmljs\qmljsdocument.h and qmljsdocument.cpp.
But the function "Follow symbol under cursor" might not work correctly, if the file has Qt.include
## -104,9 +104,13 ## public:
private:
bool parse_helper(int kind);
+ void parseQtInclude(QString dir, QString fileName, QString& result);
+
+ QList<QString> _parsedFileNames;
private:
QmlJS::Engine *_engine;
+ QmlJS::Engine *_codeCompleteEngine;
AST::Node *_ast;
Bind *_bind;
QList<QmlJS::DiagnosticMessage> _diagnosticMessages;
## -168,6 +168,7 ## QList<Language::Enum> Document::companionLanguages(Language::Enum language)
Document::Document(const QString &fileName, Language::Enum language)
: _engine(0)
+ , _codeCompleteEngine(0)
, _ast(0)
, _bind(0)
, _fileName(QDir::cleanPath(fileName))
## -197,6 +198,9 ## Document::~Document()
if (_engine)
delete _engine;
+
+ if (_codeCompleteEngine)
+ delete _codeCompleteEngine;
}
Document::MutablePtr Document::create(const QString &fileName, Language::Enum language)
## -337,9 +341,54 ## public:
} // anonymous namespace
+void Document::parseQtInclude(QString dir, QString fileName, QString& result)
+{
+
+ QFile file(dir + QDir::separator() + fileName);
+
+ if (_parsedFileNames.contains(file.fileName()) || !file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ return;
+ }
+
+ _parsedFileNames.append(file.fileName());
+
+ QFileInfo fileInfo(file);
+ QTextStream in(&file);
+ QString source = QString();
+
+ while(!in.atEnd()) {
+ source += in.read(2048);
+ }
+
+ file.close();
+ source.remove(QLatin1String(".pragma library"));
+
+ int endPos = 0;
+ int pos = source.indexOf(QLatin1String("Qt.include("), endPos);
+
+ while (pos >= 0 && pos + 11 < source.length()) {
+ QChar comma = source.at(pos + 11);
+ endPos = source.indexOf(comma + QLatin1String(")"), pos);
+ if (endPos == -1)
+ return;
+
+ QString fullStaterment = QString(source.begin() + pos, endPos - pos + 2);
+ QString importName = QString(source.begin() + pos + 12, endPos - pos - 12);
+
+ parseQtInclude(fileInfo.absolutePath(), importName, result);
+
+ source.replace(fullStaterment, QString());
+
+ pos = source.indexOf(QLatin1String("Qt.include("));
+ }
+
+ result += source;
+}
+
bool Document::parse_helper(int startToken)
{
Q_ASSERT(! _engine);
+ Q_ASSERT(! _codeCompleteEngine);
Q_ASSERT(! _ast);
Q_ASSERT(! _bind);
## -349,6 +398,31 ## bool Document::parse_helper(int startToken)
Parser parser(_engine);
QString source = _source;
+ QString fullSource = _source;
+
+ int endPos = 0;
+ int pos = fullSource.indexOf(QLatin1String("Qt.include("), endPos);
+
+ while (pos >= 0 && pos + 11 < fullSource.length()) {
+ QChar comma = fullSource.at(pos + 11);
+ endPos = fullSource.indexOf(comma + QLatin1String(")"), pos);
+ if (endPos == -1)
+ break;
+
+ QString fullStaterment = QString(fullSource.begin() + pos, endPos - pos + 2);
+ QString importName = QString(fullSource.begin() + pos + 12, endPos - pos - 12);
+ QString result = QString();
+
+ parseQtInclude(this->path(), importName, result);
+
+ fullSource.replace(fullStaterment, result);
+
+ pos = fullSource.indexOf(QLatin1String("Qt.include("));
+ if (pos == -1 || pos + 11 == source.length())
+ break;
+ comma = fullSource.at(pos + 11);
+ }
+
lexer.setCode(source, /*line = */ 1, /*qmlMode = */isQmlLikeLanguage(_language));
CollectDirectives collectDirectives(path());
## -369,9 +443,37 ## bool Document::parse_helper(int startToken)
}
_ast = parser.rootNode();
+ AST::Node *savedAst = _ast;
_diagnosticMessages = parser.diagnosticMessages();
+ if (endPos > 0) {
+ _codeCompleteEngine = new Engine();
+ Lexer lexerCodeComplete(_codeCompleteEngine);
+ Parser parserCodeComplete(_codeCompleteEngine);
+
+ bool _parsed;
+
+ lexerCodeComplete.setCode(fullSource, /*line = */ 1, /*qmlMode = */isQmlLikeLanguage(_language));
+ switch (startToken) {
+ case QmlJSGrammar::T_FEED_UI_PROGRAM:
+ _parsed = parserCodeComplete.parse();
+ break;
+ case QmlJSGrammar::T_FEED_JS_PROGRAM:
+ _parsed = parserCodeComplete.parseProgram();
+ break;
+ case QmlJSGrammar::T_FEED_JS_EXPRESSION:
+ _parsed = parserCodeComplete.parseExpression();
+ break;
+ default:
+ Q_ASSERT(0);
+ }
+
+ if (_parsed)
+ _ast = parserCodeComplete.rootNode();
+ }
+
_bind = new Bind(this, &_diagnosticMessages, collectDirectives.isLibrary, collectDirectives.imports);
+ _ast = savedAst;
return _parsedCorrectly;
}

HTML button action not working in Safari [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm running a web page in Safar, however; I notice that when I press the save button the event doesn't fire. It works fine in IE though. I've researched the issue, and found that it's not due to a missing value attribute or single/double quote specifics. Any help would be appreciated.
<input type='button' name='Save' id='saveCut' value='Save Cut' class=button onClick=\"Puma.saveTheCut()\">
JS function
Puma.saveTheCut = function () {
var offerId = inStoreCut.cutOfferFields[0];
var merchId = inStoreCut.cutOfferFields[1];
var adId = inStoreCut.cutOfferFields[2];
var eventID = inStoreCut.cutOfferFields[3];
var adNum = inStoreCut.cutOfferFields[4];
var cutID = inStoreCut.cutOfferFields[5];
var merchDescription = parent.main.document.getElementById('merchDescription').value;
var UPC = parent.main.document.getElementById('merchUPC').value;
var nrfSampleColorObj = parent.main.document.getElementById('itemColor');
var nrfSampleColor = nrfSampleColorObj.options[nrfSampleColorObj.selectedIndex].value;
var nrfsampleSubColorObj = parent.main.document.getElementById('itemChildColor');
var colorCodeStr = nrfsampleSubColorObj.options[nrfsampleSubColorObj.selectedIndex].value;
var nrfsampleSubColor = colorCodeStr.substring(0, 3);
var customer_Facing_Color = parent.main.document.getElementById('merchCustomerFacingColor').value;
var division = parent.main.document.getElementById('merchFob').value;
var deptNum = parent.main.document.getElementById('merchDept0~0').value;
var vendorNum = parent.main.document.getElementById('merchVendorNum0~0').value;
var pID = parent.main.document.getElementById('pID0~0').value;
var regPrice = parent.main.document.getElementById('regPrice').value;
var sampleSize = parent.main.document.getElementById('itemSize').value;
var itemQty = parent.main.document.getElementById('itemQty').value;
if (parent.main.document.getElementById('chkMerchSet').checked) {
var set = "1";
}
else {
var set = "0";
}
var sampleTypeObj = parent.main.document.getElementById("itemType");
var sampleType = sampleTypeObj.options[sampleTypeObj.selectedIndex].text;
var merchColorCorrObj = parent.main.document.getElementById("merchColorCorr");
var colorCorr = merchColorCorrObj.options[merchColorCorrObj.selectedIndex].value;
var merchSwatchObj = parent.main.document.getElementById("merchSwatch");
var Swatch = merchSwatchObj.options[merchSwatchObj.selectedIndex].value;
var pantoneColor = parent.main.document.getElementById('merchPantone').value;
var photoStylingDetails = parent.main.document.getElementById('merchPhotoStylingDetails').value;
var mCOMSampleId = parent.main.document.getElementById('mCOMSample').value;
var deptName = parent.main.document.getElementById('merchDeptName0~0').innerHTML;
var vendorName = Puma.decoder(parent.main.document.getElementById('merchVendorName0~0').innerHTML);
if (parent.main.document.getElementById('pidStatus0~0').value == "NOT IN PD") {
var pidStatus = "0";
}
else {
var pidStatus = "1";
}
var pidDescription = parent.main.document.getElementById('pidDescription').value;
var webId = parent.main.document.getElementById('webID0~0').innerHTML;
var vStyle = parent.main.document.getElementById('merchVStyle').value;
var markStyle = parent.main.document.getElementById('merchMarkStyle').value;
var subClass = parent.main.document.getElementById('Subclass').value;
// var productDescription = parent.main.document.getElementById('productDescription').value;
var docLineitemNum = parent.main.document.getElementById('merchDoc').value;
var merchTurnInStatusObj = parent.main.document.getElementById("merchTurnInStatus");
var turnInStatus = merchTurnInStatusObj.options[merchTurnInStatusObj.selectedIndex].text;
var reason = parent.main.document.getElementById('merchReason').value;
var merchCountryOriginObj = parent.main.document.getElementById("countryOfOrigin");
var countryOfOrigin = merchCountryOriginObj.options[merchCountryOriginObj.selectedIndex].value;
var importedCountry = parent.main.document.getElementById("importedCountries").value;
//var importedCountry = merchImportedCountryObj.options[merchImportedCountryObj.selectedIndex].text;
var fabricContent = parent.main.document.getElementById("fabricContent").value;
var careInstructions = parent.main.document.getElementById("careInstructions").value;
var offerDescription = parent.main.document.getElementById("offerDescription").value;
var onlyAtMacysObj = parent.main.document.getElementById("onlyAtMacys");
var onlyAtMacysValue = parseInt(onlyAtMacysObj.options[onlyAtMacysObj.selectedIndex].value, 10);
var onlyAtMacys = onlyAtMacysValue;
var legalOneObj = parent.main.document.getElementById("legalOne");
var legalOne = legalOneObj.options[legalOneObj.selectedIndex].value;
var legalOneExplain = parent.main.document.getElementById("explainLegalOne").value;
var legalTwoObj = parent.main.document.getElementById("legalTwo");
var legalTwo = legalTwoObj.options[legalTwoObj.selectedIndex].value;
var legalTwoExplain = parent.main.document.getElementById("explainLegalTwo").value;
var legalThreeObj = parent.main.document.getElementById("legalThree");
var legalThree = legalThreeObj.options[legalThreeObj.selectedIndex].value;
var legalThreeExplain = parent.main.document.getElementById("explainLegalThree").value;
var legalFourObj = parent.main.document.getElementById("legalFour");
var legalFour = legalFourObj.options[legalFourObj.selectedIndex].value;
var fiftyObj = parent.main.document.getElementById("overFifty");
var fifty = fiftyObj.options[fiftyObj.selectedIndex].value;
var userId = parent.botnav.uinfo.userID;
if (Puma.btiRequiredFieldIsValidated() == true) {
if (inStoreCut.existingRecord == false) {
sql = "action=saveMerchFormForCut&cutID=" + cutID +
//sql = "action=updateMerchFormForCut&cutID=" + cutID +
"&merchDescription=" + encodeURIComponent(merchDescription) +
"&UPC=" + UPC +
"&nrfSampleColor=" + nrfSampleColor +
"&nrfSampleSubColor=" + nrfsampleSubColor +
"&division=" + encodeURIComponent(division) +
"&deptNum=" + deptNum +
"&merchVendorNum=" + vendorNum +
"&pID=" + pID +
"&Customer_Facing_Color=" + encodeURIComponent(customer_Facing_Color) +
"&regPrice=" + regPrice +
"&sampleSize=" + encodeURIComponent(sampleSize) +
"&itemQty=" + itemQty +
"&set=" + set +
"&sampleType=" + sampleType +
"&colorCorr=" + colorCorr +
"&Swatch=" + Swatch +
"&pantoneColor=" + encodeURIComponent(pantoneColor) +
"&photoStylingDetails=" + encodeURIComponent(photoStylingDetails) +
"&mCOMSampleId=" + mCOMSampleId +
"&deptName=" + deptName +
"&vendorName=" + encodeURIComponent(vendorName) +
"&pidStatus=" + pidStatus +
"&pidDescription=" + pidDescription +
"&webId=" + webId +
"&vStyle=" + vStyle +
"&markStyle=" + markStyle +
"&subClass=" + subClass +
"&docLineItemNum=" + docLineitemNum +
"&merchTurnInStatus=" + turnInStatus +
"&reason=" + encodeURIComponent(reason) +
"&countryOfOrigin=" + countryOfOrigin +
"&importedCountry=" + importedCountry +
"&fabricContent=" + encodeURIComponent(fabricContent) +
"&careInstructions=" + encodeURIComponent(careInstructions) +
"&offerDescription=" + encodeURIComponent(offerDescription) +
"&onlyAtMacys=" + onlyAtMacys +
"&legalOne=" + legalOne +
"&legalOneExplain=" + legalOneExplain +
"&legalTwo=" + legalTwo +
"&legalTwoExplain=" + legalTwoExplain +
"&legalThree=" + legalThree +
"&legalThreeExplain=" + legalThree +
"&legalFour=" + legalFour +
"&fifty=" + fifty +
"&createdBy=" + userId
var ajaxMaster = new AjaxMaster(sql, "Puma.saveMerchFormForCutData(data)", "", "btiDispatcher.aspx");
sql = "action=updateMerchFormForCut&sql=" + encodeURIComponent(msql);
objAjaxAd.main_flag = "updateMerchFormForCut";
objAjaxAd.SendQuery(sql);
// "[t0].[signedByUserID]," +
// "[t0].[signedStatus]," +
//"[t0].[dateSigned]," +
//"[t0].[signedLastByUserID]," +
//"[t0].[dateLastSigned1]," +
//"[t0].[signedLastStatus]" +
// var ajaxMaster = new AjaxMaster(sql, "Puma.updateMerchFormForCutData(data)", "", "puma_core.aspx");
}
else {
sql = "action=updateMerchFormForCut&cutID=" + cutID +
"&offerId" + offerId +
"&merchId" + merchId +
"&adID" + adId +
"&eventID" + eventID +
"&adNum" + adNum +
"&merchDescription=" + encodeURIComponent(merchDescription) +
"&UPC=" + UPC +
"&nrfSampleColor=" + nrfSampleColor +
"&nrfSampleSubColor=" + nrfsampleSubColor +
"&division=" + encodeURIComponent(division) +
"&deptNum=" + deptNum +
"&merchVendorNum=" + vendorNum +
"&pID=" + pID +
"&Customer_Facing_Color=" + encodeURIComponent(customer_Facing_Color) +
"&regPrice=" + regPrice +
"&sampleSize=" + encodeURIComponent(sampleSize) +
"&itemQty=" + itemQty +
"&set=" + set +
"&sampleType=" + sampleType +
"&colorCorr=" + colorCorr +
"&Swatch=" + Swatch +
"&pantoneColor=" + encodeURIComponent(pantoneColor) +
"&photoStylingDetails=" + encodeURIComponent(photoStylingDetails) +
"&mCOMSampleId=" + mCOMSampleId +
"&deptName=" + deptName +
"&vendorName=" + encodeURIComponent(vendorName) +
"&pidStatus=" + pidStatus +
"&pidDescription=" + pidDescription +
"&webId=" + webId +
"&vStyle=" + vStyle +
"&markStyle=" + markStyle +
"&subClass=" + subClass +
"&docLineItemNum=" + docLineitemNum +
"&merchTurnInStatus=" + turnInStatus +
"&reason=" + encodeURIComponent(reason) +
"&countryOfOrigin=" + countryOfOrigin +
"&importedCountry=" + importedCountry +
"&fabricContent=" + encodeURIComponent(fabricContent) +
"&careInstructions=" + encodeURIComponent(careInstructions) +
"&offerDescription=" + encodeURIComponent(offerDescription) +
"&onlyAtMacys=" + onlyAtMacys +
"&legalOne=" + legalOne +
"&legalOneExplain=" + legalOneExplain +
"&legalTwo=" + legalTwo +
"&legalTwoExplain=" + legalTwoExplain +
"&legalThree=" + legalThree +
"&legalThreeExplain=" + legalThree +
"&legalFour=" + legalFour +
"&fifty=" + fifty +
//"&createdBy=" + userId
"&offerId=" + offerId +
"&merchId=" + merchId +
"&adID=" + adId +
"&eventID=" + eventID +
"&adNum=" + adNum
var ajaxMaster = new AjaxMaster(sql, "Puma.updateMerchFormForCutData(data)", "", "btiDispatcher.aspx");
sql = "action=updateMerchFormForCut&sql=" + encodeURIComponent(msql);
//objAjaxAd.SendQuery(sql);
// "[t0].[signedByUserID]," +
// "[t0].[signedStatus]," +
//"[t0].[dateSigned]," +
//"[t0].[signedLastByUserID]," +
//"[t0].[dateLastSigned1]," +
//"[t0].[signedLastStatus]" +
objAjaxAd.main_flag = "updateMerchFormForCutData";
objAjaxAd.SendQuery(sql);
//var ajaxMaster = new AjaxMaster(sql, "Puma.updateMerchFormForCutData(data)", "", "puma_core.aspx");
}
}
}
Write just " and not \" in the onClick attribute, or just omit the quotation marks:
onClick=Puma.saveTheCut()
The character \ has no special role in HTML; it’s just yet another character. So when you have onClick=\"Puma.saveTheCut()\", the actual attribute value is \"Puma.saveTheCut()\", which does not work of course, as you can see by looking at the console in the Developer Tools of your browser. You should see something the like following there:
SyntaxError: illegal character
\"Puma.saveTheCut()\"
(or with \"yup()\" when testing Agony’s jsfiddle).
As it is, the code should not work in any browser, and does not work in my IE 10 either.

Compare month in nested object array

The following problem is causing me some headache. I'm building an application to compare transaction data with a list of tenants and what they're supposed to pay for rent.
I've got it running nicely except it compares EACH transaction with the monthly rent. What I want to do is first add all (relevant) transaction amounts per month and then compare them.
Should I just build another nested for-loop to compare all the transaction months before I run this loop? I could potentially drop in years of transaction data making it quite inefficient...
Any tips are greatly appreciated.
var table = "<table><thead><tr><th>Rek</th><th>Name</th><th>Date</th><th>Amount</th><th>Rent</th><th>Diff</th></tr></thead><tbody>";
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < tenant.length; j++) {
if (tenant[j].reks.indexOf(data[i].rek) == -1)
continue;
else {
var diff = tenant[j].rent - data[i].amount; //TODO monthly!!!
var style = " style='background-color: ";
if (diff > 0)
style += "red;'";
else
style += "green;'";
table += "<tr><td>" + data[i].rek
+ "</td><td>" + data[i].name
+ "</td><td>" + (data[i].date.getMonth() + 1) + "-" + data[i].date.getFullYear()
+ "</td><td>€ " + data[i].amount
+ "</td><td>€ " + tenant[j].rent
+ "</td><td" + style
+ ">" + diff
+ "</td></tr>";
}
}
}
table += "</tbody></table>";
$('#top').html(table);

Passing parameters to a form, via JavaScript

I have a form which passes a number of parameters. So far, the stock parameters are being passed:
var params = "title=" + document.getElementById("title").value +
"&url=" + document.getElementById("url").value +
"&snippet=" + document.getElementById("snippet").value +
"&tags=" + document.getElementById("tags").value +
"&status_bookmark=" + document.getElementById("status_bookmark").value +
"&comment=" + document.getElementById("comment").value +
"&status_comment=" + document.getElementById("status_comment").value;
I'm attempting to append additional form elements to this parameter string, which are:
var i, lng = document.getElementById('addbookmark').length;
// If the length property is undefined, then there is only one checkbox.
if (typeof lng === "undefined") {
params + "&topic-link-item-1=" + document.getElementById("topic-link-item-1").value;
params + "&topic-link-comment-box-1=" + document.getElementById("topic-link-comment-box-1").value;
}
else {
for (i = 0; i < lng; i++) {
params + "&topic-link-item-" + i + "=" + document.getElementById("topic-link-item-" + i).value;
params + "&topic-link-comment-box-" + i + "=" + document.getElementById("topic-link-comment-box-" + i).value;
}
}
Here, I've used code taken from another StackOverflow article, and as you can see, I'm trying to build up a series of paired parameters that match the ad hoc form elements I'm generating elsewhere via jQuery, which works.
However, these values appear not be getting passed via the form, while the other form elements are being passed.
Any suggestions?
Update
I've revised the code, per the suggestions, but it's not working:
var i, formObj = document.form['addbookmark'], formObjLng = document.form['addbookmark'].length;
// If the length property is undefined, then there is only one checkbox.
if ((typeof formObjLng !== "undefined")) {
for (i = 0; i < formObjLng; i++) {
if ((formObj.elements['topic-link-item-' + i].type == "checkbox") && (formObj.elements['topic-link-item-' + i].checked)) {
params = params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i)).value;
params = params + "&topic-link-comment-box-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-comment-box-" + i)).value;
}
}
}
As for the form, it's simply a form with an ID of "addbookmark", and to again state what I said earlier, everything else works with the exception of what Im attempting here.
There are 2 issues with your code. You need to URL encode the values using the encodeURIComponent function. Also you need to assign the result back to the params variable when concatenating:
var params =
"title=" + encodeURIComponent(document.getElementById("title").value) +
"&url=" + encodeURIComponent(document.getElementById("url").value) +
"&snippet=" + encodeURIComponent(document.getElementById("snippet").value) +
"&tags=" + encodeURIComponent(document.getElementById("tags").value) +
"&status_bookmark=" + encodeURIComponent(document.getElementById("status_bookmark").value) +
"&comment=" + encodeURIComponent(document.getElementById("comment").value) +
"&status_comment=" + encodeURIComponent(document.getElementById("status_comment").value);
and also for the other values that you are adding:
var i, lng = document.getElementById('addbookmark').length;
// If the length property is undefined, then there is only one checkbox.
if (typeof lng === "undefined") {
params += "&topic-link-item-1=" + encodeURIComponent(document.getElementById("topic-link-item-1").value);
params += "&topic-link-comment-box-1=" + encodeURIComponent(document.getElementById("topic-link-comment-box-1").value);
}
else {
for (i = 0; i < lng; i++) {
params += "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
params += "&topic-link-comment-box-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-comment-box-" + i).value);
}
}
Notice how:
params += "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
which is equivalent to:
params = params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
is not the same as what you were doing initially:
params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
You were simply concatenating 2 values and never assigning the result back to the params variable.
I'm pretty sure Javascript doesnt' allow text append the way you are doing it.
Should be
params = params +

Categories