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

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

Related

issue between browsers with date pad function

I am trying to convert a date to a string and I am finding that my method works in firefox. But the same code comes up with a different and wrong time in both safari and chrome. I've put my code below. Can anyone see what might be wrong.
$(document).ready(function() {
var regLastSynchTime = new Date(item.date);
regLastSynchTimeStr = formattedTradingHourDateAndTime(regLastSynchTime);
});
var formattedTradingHourDateAndTime = function(date){
var d = pad(date.getDate());
var m = pad(date.getMonth() + 1);
var y = date.getFullYear();
var h = pad(date.getHours());
var mi = pad(date.getMinutes());
var ss = pad(date.getSeconds());
return d + '/'+ m + '/'+y + ' ' + h + ':' + mi + ':' + ss;
}
function pad(number) {
return (number < 10 ? '0' : '') + number;
}
Firefox (right)
Safari (Wrong)

How to fix this js code?

I didn't write this code, but I'm still a beginner, can anyone help me with the bugs in this? JSLint kept giving me several bugs and I couldn't seem to fix them. It would be every much appreciated. I'm learning as I post this. I'm currently working on improving my graphic/motion design skills and coding skills. But I can't write something like this currently. If there is anymore detail you need, you can just comment and ask. Thanks.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://209.15.211.170/catalog/", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
$("html").html("<h2 style='position:absolute;left:60%;color:#BF34334;font-family:arial;'></h2>");
var minPage = 1;
var maxPage = 12;
var page = minPage;
var json = 'http://209.15.25843811.170/catalog/json?browse&Category=2';
var min = 1;
var max = Number(prompt("Maximum Robux?"));
function buy(item, price) {
"use strict";
var link = 'http://209.15.211.170/';
$.get(link, function(data) {
var info = (data).find('.ItemSalesTable'.find('.PurchaseButton')).data();
var buy = 'http://www.roblox.com/API/Item.aspx?rqtype=purchase&productID=' + info[productId] + '&expectedcurrency=1&expectedPrice=' + info[expectedPrice] + '&expectedSellerId=' + info[expectedSellerId] + & userAssetID = +info[userassetId];
if (parseInt(info) == parseInt(info['expectedPrice'])) {}
});
}
setInterval(function(3000) {
function get() {
$.get(json, function(Data) {
for (var Hat & Data {
if (max >= Price && Price > 0) {
buy(ID, Price)
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.info(Name + '[' + Price + '] # ' + time);
}
}
})
}
get()
console.clear();
console.info('Running on pages ' + minPage + '-' + maxPage);
confirm = function() {};
alert = function() {};
console.clear();
Not entirely sure what your needs are, but try replacing your code with this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://209.15.211.170/catalog/", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
$("html").html("<h2 style='position:absolute;left:60%;color:#BF34334;font-family:arial;'></h2>");
var minPage = 1;
var maxPage = 12;
var page = minPage;
var json = 'http://209.15.25843811.170/catalog/json?browse&Category=2';
var min = 1;
var max = Number(prompt("Maximum Robux?"));
function buy(item, price) {
"use strict";
var link = 'http://209.15.211.170/';
$.get(link, function(data) {
var info = (data).find('.ItemSalesTable'.find('.PurchaseButton')).data();
var buy = 'http://www.roblox.com/API/Item.aspx?rqtype=purchase&productID=' + info[productId] + '&expectedcurrency=1&expectedPrice=' + info[expectedPrice] + '&expectedSellerId=' + info[expectedSellerId] + '&userAssetID=' +info[userassetId];
if (parseInt(info) == parseInt(info['expectedPrice'])) {}
});
};
function get() {
$.get(json, function(Data) {
for (var Hat in Data) {
if (max >= Price && Price > 0) {
buy(ID, Price);
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.info(Name + '[' + Price + '] # ' + time);
}
}
});
};
setInterval(function() {
get();
console.clear();
console.info('Running on pages ' + minPage + '-' + maxPage);
confirm = function() {};
alert = function() {};
console.clear();
}, 3000);

SQL node.js Syntax error on what seems to be a valid query?

I'm running an update on a table to set a position. I've extracted the query and manually run it on my database and works fine but when passed through connection.query() it seems to think there's a syntax error in my node.js console.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
var input = ', moving_datetime = ' + datetime;
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}
Here is the syntax error:
Here's the input data value of 'position' variable:
{ x: '-605', y: '-257', moving: 0 }
I hope I'm not being too much of a dunce and sorry for the low quality question.
Thanks
This function will generate SQL code which is missing quotes around the datetime variable, resulting in invalid SQL code.
function sendShipPosition(position) {
var input = '';
if (position.moving === true) {
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
# Here!
var input = ', moving_datetime = \'' + datetime + '\''
}
connection.query('UPDATE ships SET x_axis = :x, y_axis = :y' + input + ' WHERE ship_id = :ship_id'), {
x: parseInt(position.x),
y: parseInt(position.y),
ship_id: 1
};
}

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

Rename file name with javascript expression

I'm fairly new to javascript and I need to rename or add to an extension of a css and .png file. The script is embedded within an ETL process. I have a variable "prd" that holds the value of the file name that the style.css and picture.png file are derived from and I also need to add a date or time stamp to the end of the extension. Basically I'm wanting to concatenate prd+style_02_06_14.png
Desired results:
Prd = sales_report
File = style.css.
Result = "sales_report_style_02_06_14.png" and "sales_report_style_02_06_14.css"
Here is my code
var sourceCssFile = outputfolder + "style.css";
var destinationCssFile = outputfolder + css_pic;
if(isFolder(destinationCssFile) == false) {
createFolder(destinationCssFile);
var testvar = "inside";
}
destinationCssFile = destinationCssFile + "/style.css";
moveFile(sourceCssFile, destinationCssFile, true);
var sourceImageFile = outputfolder + "picture.png";
var destinationImageFile = outputfolder + css_pic + "/picture.png";
moveFile(sourceImageFile, destinationImageFile, true);
var cont = loadFileContent(output);
var replaceCss = css_pic + "tt+style.css";
var replaceImg = css_pic + "tt + picture.png";
cont = cont.replace("style.css", replaceCss);
cont = cont.replace("picture.png", replaceImg);
var filename = outputfolder + new_str;
Try this:
function formatResult(prd, filename, date, extension) {
return prd + '_' + filename + '_' + formatDate(d) + '.' + extension;
}
function formatDate(d) {
var year = d.getFullYear().toString().substr(2,2);
var month = (d.getMonth()+1) + '';
if (month.length == 1) {
month = "0" + month;
}
var day = d.getDate() + '';
if (day.length == 1) {
day = "0" + day;
}
return month + '_' + day + '_' + year;
}
Demo
http://jsfiddle.net/WHpuU/5/
Nota
alert( 'style.css'.replace(/\.css$/i, '') ); // shows 'style'

Categories