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

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;
}

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.

Generate random equations with random numbers [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 6 years ago.
Improve this question
I want to generate random equations in JavaScriptp and then output them into an HTML tag.
This is the code:
<!DOCTYPE html>
<body>
<p>Click the button below to generate a random equation.</p>
<button onclick="change();">Generate</button>
<p id="generate"></p>
<script>
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
function getRandomNumber(results) {
var rollDie = getRandomizer( 1, 10 );
for ( var i = 0; i < 3; i++ ) {
results += rollDie() + "";
}
getRandomNumber.result = results;
}
function getRandomEquation(num1, num2, num3, num4, num5, num6, num7, output) {
var num_7,
num_6,
num_5,
num_4,
num_3,
num_2,
num_1
getRandomNumber(num1).result = num_7;
getRandomNumber(num2).result = num_6;
getRandomNumber(num3).result = num_5;
getRandomNumber(num4).result = num_4;
getRandomNumber(num5).result = num_3;
getRandomNumber(num6).result = num_2;
getRandomNumber(num7).result = num_1;
var equation1 = "" + num_1 + " x " + num_2 + " + {" + num_3 + " x [(" + num_4 + " x " + num_5 + ") - " + num_6 + "] + " + num_7 + "} = x",
equation2 = "" + num_1 + " x " + num_2 + " = y",
equation3 = "" + num_1 + "s x " + num_2 + " = z, s = " + num_3,
equation4 = "" + num_1 + " + {" + num_2 + " x [" + num_3 + " + (" + num_4 + " x " + num_5 + ") + " + num_6 + "] + " + num_7 + "} = x",
equation5 = "" + num_1 + "e + " + num_2 + "l x " + num_3 + " + " + num_4 + "a, e = " + num_5 + ", l = " + num_6 + ", a = " + num_7,
equation6 = "[" + num_1 + " x " + num_2 + "z] + {" + num_3 + " - " + num_4 + "} + (" + num_5 + " + " + num_6 + ") = e, z = " + num_7,
equation7 = "p" + " x " + num_1 + " / " + num_2 + " - " + num_3 + " + " + num_4 + " = e, p = " + num_5
var values = [
// there is an easier way to do this, too lazy
"" + equation1,
"" + equation2,
"" + equation3,
"" + equation4,
"" + equation5,
"" + equation6,
"" + equation7
]
var i = 0;
var e;
if (i > values.length) {
i = 0;
}
var randomEquation = values[i];
i++;
e = values[i];
this.output = randomEquation;
this.e = e;
}
function getEquation() {
var bl1,
bl2,
bl3,
bl4,
bl5,
bl6,
bl7,
equationOutput;
var eq = getRandomEquation(bl1, bl2, bl3, bl4, bl5, bl6, bl7, equationOutput).e;
getEquation.equation = eq;
}
function change() {
var final = getEquation().equation;
document.getElementById("generate").innerHTML = final;
}
</script>
</body>
</html>
But it dosen't work. Any help?
P.S. My teacher assigned this to me. Please respond as soon as possible. Thanks.
This code is a complete mess. I dont know where it comes from, but definitely not Javascript.
Try the following instead:
<!DOCTYPE html>
<body>
<p>Click the button below to generate a random equation.</p>
<button onclick="change();">Generate</button>
<p id="generate"></p>
<script>
function getRandomizer(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
function getRandomNumber() {
var results="";
for ( var i = 0; i < 3; i++ ) {
results += getRandomizer( 1, 10 );
}
return results;
}
function getRandomEquation() {
var num_7 = getRandomNumber(),
num_6 = getRandomNumber(),
num_5 = getRandomNumber(),
num_4 = getRandomNumber(),
num_3 = getRandomNumber(),
num_2 = getRandomNumber(),
num_1 = getRandomNumber();
var equation1 = num_1+" x "+num_2+" + {"+num_3+" x [("+num_4+" x "+num_5+") - "+num_6+"] + "+num_7+"} = x",
equation2 = num_1+" x "+num_2+" = y",
equation3 = num_1+"s x "+num_2+" = z, s = "+num_3,
equation4 = num_1+" + {" +num_2+ " x [" +num_3+" + ("+num_4+" x "+num_5+") + "+num_6+"] + "+num_7+"} = x",
equation5 = num_1+"e + "+num_2+"l x "+num_3+" + "+num_4+"a, e = "+num_5+", l = "+num_6+", a = "+ num_7,
equation6 = "["+num_1+" x "+num_2+ "z] + {"+num_3+" - "+num_4+"} + ("+num_5+" + "+num_6+") = e, z = "+ num_7,
equation7 = "p x "+num_1+" / "+num_2+" - "+num_3+" + "+num_4+" = e, p = "+num_5
var randomEquation = [
equation1,
equation2,
equation3,
equation4,
equation5,
equation6,
equation7
]
return randomEquation.join("<br>");
}
function change() {
document.getElementById("generate").innerHTML = getRandomEquation();
}
</script>
</body>
</html>
Well, you could do this:
var type = (Math.floor(Math.random(4));
var ret = 0;
var n = [(Math.floor(Math.random(100)), (Math.floor(Math.random(100))];
if (type == 0) ret = n[0] + n[1]
else if (type == 1) ret = Math.abs(n[0] - n[1])
else if (type == 2) ret = n[0] * n[1];
else if (type == 3) ret = n[0] / n[1]
else ret = n[0] / 5 % n[1]
// do something with ret
It's fully expandable, just edit n and the if statements

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.

Javascript - How do I capture and respond to a post?

I am developing an application to respond to a punch out, but am missing something. I can create the reponse XML document fine, but the receiving end is not seeing my response. I have found hundreds of examples on the web about the post process, but cannot seem to figure out what the server is supposed to do to reply to the post. If anyone can offer an example of the server side of this, that would be greatly appreciated.
Update
Here is the code that I have. I did replace the SEND with a display to see what it was I am trying to send. I am very new to this, so any insight would be helpful.
<script language="javascript">
var xmlhttp;
var xmlrtn;
<!-- Begin
Stamp = new Date();
year = Stamp.getYear();
month = Stamp.getMonth() + 1;
if (month < 10) {month = "0" + month;}
ddate = Stamp.getDate();
if (ddate < 10) {ddate = "0" + ddate;}
if (year < 2000) year = 1900 + year;
//document.write(year + "-" + month + "-" + ddate);
timestamp = year + "-" + month + "-" + ddate;
var Hours;
var Mins;
var Time;
Hours = Stamp.getHours();
Mins = Stamp.getMinutes();
if (Mins < 10) {
Mins = "0" + Mins;
}
Secs = Stamp.getSeconds();
if (Secs < 10) {Secs = "0" + Secs;}
//document.write('T' + Hours + ":" + Mins + ":" + Secs);
timestamp = timestamp + 'T' + Hours + ":" + Mins + ":" + Secs;
// End -->
xmlhttp=new ActiveXObject("Microsoft.XMLDOM");
var o="<";
var c="/" + ">";
var tc="<" + "/";
var e=">";
var params=new Array();
var xmlrtn = '';
function loadXML(xmlFile)
{
xmlhttp.async="false";
xmlhttp.onreadystatechange=verify;
xmlhttp.load(xmlFile);
xmlObj=xmlhttp.documentElement;
}
function verify()
{
// 0 Object is not initialized
// 1 Loading object is loading data
// 2 Loaded object has loaded data
// 3 Data from object can be worked with
// 4 Object completely initialized
if (xmlhttp.readyState != 4)
{
return false;
}
}
</script>
</head>
<body>
<script language="javascript">
//Read in XML file
loadXML('https://www.americantexchem.com:9443/storefrontContent/attach/sample.xml');
//Assign Variables
var xmlver='?xml version="1.0"?';
var doctype='!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.1.007/cXML.dtd"';
xmlLang=xmlObj.getAttribute("xml:lang");
var cxmltag=xmlObj.tagName;
var cxmlval=' version="' + xmlObj.getAttribute("version") + '" payloadID="' + xmlObj.getAttribute("payloadID") + '" timestamp="' + timestamp + '"';
var resptag='Response';
var statustag='Status code="200" text="success" ';
var poutsrtag='PunchOutSetupResponse';
var startpgtag='StartPage';
var urltag='URL';
var urlval='https://www.americantexchem.com:9443/storefrontCommerce/jsp/wynlogin.jsp';
var srcurlval = xmlObj.childNodes(1).childNodes(0).childNodes(2).childNodes(0).firstChild.text; //URL content
// post
params[0] = o + xmlver + e;
params[1] = o + doctype + e;
params[2] = o + cxmltag;
params[3] = cxmlval + e;
params[4] = o + resptag + e;
params[5] = o + statustag + c;
params[6] = o + poutsrtag + e;
params[7] = o + startpgtag + e;
params[8] = o + urltag + e;
params[9] = urlval;
params[10] = tc + urltag + e;
params[11] = tc + startpgtag + e;
params[12] = tc + poutsrtag + e;
params[13] = tc + resptag + e;
params[14] = tc + cxmltag + e;
for (var i in params) {
if (params.hasOwnProperty(i)) {
// var input = document.createElement('input');
// input.type = 'hidden';
// input.name = i;
//input.value = params[i];
// form.appendChild(input);
xmlrtn = xmlrtn + params[i];
}
}
// alert (xmlObj.xml);
document.write (xmlrtn);
/*
var fso = new ActiveXObject("Scripting.FileSystemObject");
fileBool = fso.FileExists("C:\\out.xml");
if(fileBool)
{
//document.write("Test-fileBool");
fso.DeleteFile("C:\\out.xml",true);
}
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.OpenTextFile("C:\\out.xml" , 8, true);
s.writeline (o + xmlver + e);
s.writeline (o + doctype + e);
s.writeline (o + cxmltag);
s.writeline (cxmlval + e);
s.writeline (o + resptag + e);
s.writeline (o + statustag + c);
s.writeline (o + poutsrtag + e);
s.writeline (o + startpgtag + e);
s.writeline (o + urltag + e);
s.writeline (urlval);
s.writeline (tc + urltag + e);
s.writeline (tc + startpgtag + e);
s.writeline (tc + poutsrtag + e);
s.writeline (tc + resptag + e);
s.writeline (tc + cxmltag + e);
// s.writeline (xmlObj.xml); // the whole source xml document
s.Close();
*/
</script>
</body>
</html>
This will depend a bit on your server side technology. Here is an example post using asp.net mvc.
http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
Hope this helps getting you started
Bob

Cannot collect alle results of asynchronous call with geo.getLocations (Google Maps)

Below is my code. The problem is that recordsOut[0] is always undefined, whatever I try.
I know it has to do with the callback result. I tried to add some delays to give it more time to give a result back, but that did not help.
Any idea (with example please)? Very much appreciated.
function getAddress(id, searchValue) {
geo.getLocations(searchValue, function(result) {
if (result.Status.code == G_GEO_SUCCESS) {
var recordsOutStr = id + ';' + searchValue + ';';
for (var j = 0; j < result.Placemark.length; j++)
recordsOutStr += result.Placemark[j].address + ';' + result.Placemark[j].Point.coordinates[0] + ';' + result.Placemark[j].Point.coordinates[1];
recordsOut.push(recordsOutStr);
alert(recordsOutStr);
}
else {
var reason = "Code " + result.Status.code;
if (reasons[result.Status.code])
reason = reasons[result.Status.code]
alert('Could not find "' + searchValue + '" ' + reason);
}
});
}
function delay(ms)
{
var date = new Date();
var curDate = null;
do
{
curDate = new Date();
}
while (curDate - date < ms);
}
function processData()
{
objDataIn = document.getElementById("dataIn");
objDataOut = document.getElementById("dataOut");
if (objDataIn != null)
{
//alert(objDataIn.value);
if (objDataOut != null) {
recordsIn = explode(objDataIn.value, ';', true);
//for (i = 0; i < recordsIn.length; i++)
for (i = 0; i <= 5; i++)
{
addressStr = recordsIn[i]['address'] + ', ' +
recordsIn[i]['postalcode'] + ' ' +
recordsIn[i]['city'] + ', ' +
recordsIn[i]['country'];
getAddress(recordsIn[i]['id'], addressStr); //This will set resultStr
delay(200);
}
delay(5000);
alert('***' + recordsOut[0] + '***');
alert('***' + recordsOut[1] + '***');
alert('***' + recordsOut[2] + '***');
alert('***' + recordsOut[3] + '***');
alert('***' + recordsOut[4] + '***');
}
}
document.frmGeoCoder.submit();
}
Make sure that you have already defined recordsOut like this:
var recordsOut = [];
If you do it like this - var recordsOut; - it will be undefined.
If that doesn't work for you, please post the rest of the code, so we can see exactly what's going on.

Categories