Significance of '&' Symbol in JavaScript - javascript
I am currently working on a form that posts data to SAP. I am using JavaScript to invoke a Web Service to do this. I am running into an issue where one of the fields in the form has the value of 'GT&N' and I only get an error when the '&' symbol is present. I have looked on Google but have found nothing in relation the the & Symbol and JavaScript.
Error Message I'm receiving from the Web Page:
Unexpected end of file. Following elements are not closed: Characteristic_Value, RunParameter, Run, Body, Envelope. Line 1, position 2520
**The 'Characteristic_Value' is my field within the form.
Error I see when I debug:
Whenever I do not use the '&' Symbol, everything works great. I also tried using other special charecters and it posts just fine.
There is quite a bit of code to this so I am not going to post all of it unless requested as this is just a general question in regards to the '&' Symbol and JavaScript.
The JavaScript Code
//Create
var WebServer = "http://webserver";
var WebServiceName = "CreateIngredient";
var ScriptType = "Transaction";
var RepeatingTableXMLPath = "/my:myFields/my:CreateIngredient/my:CreateIngredient_Repeat";
// To Call Web service from infopath
function CreateIngredient(theXmlNode) {
//Add parameter into the request
var addBatchRequest = new SOAPClientParameters();
var Addresses = new Array();
var AddressXmlNodes = theXmlNode.selectNodes(RepeatingTableXMLPath);
// Loop for Input Field from Repeating Table
for (var i = 0; i < AddressXmlNodes.length; i++) {
var xPath = AddressXmlNodes[i].getXPath();
// Input field, It can be n number of fields
addBatchRequest.add("Material_description", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material_description").getValue());
addBatchRequest.add("Base_Unit_of_Measure", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Base_Unit_of_Measure").getValue());
addBatchRequest.add("Material_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material_group").getValue());
addBatchRequest.add("External_Material_Group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:External_Material_Group").getValue());
addBatchRequest.add("Division", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Division").getValue());
addBatchRequest.add("Authorization_Group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Authorization_Group").getValue());
addBatchRequest.add("Gross_weight", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Gross_weight").getValue());
addBatchRequest.add("Weight_Unit", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Weight_Unit").getValue());
addBatchRequest.add("Net_weight", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Net_weight").getValue());
addBatchRequest.add("Dangerous_Goods_Indicator_Profile", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Dangerous_Goods_Indicator_Profile").getValue());
addBatchRequest.add("Class_number", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Class_number").getValue());
addBatchRequest.add("Characteristic_Value", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Characteristic_Value").getValue().toString());
addBatchRequest.add("Class_number1", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Class_number1").getValue());
addBatchRequest.add("Plant", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Plant").getValue());
addBatchRequest.add("Checking_Group_for_Availability_Check", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Checking_Group_for_Availability_Check").getValue());
addBatchRequest.add("Batch_management_requirement_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Batch_management_requirement_indicator").getValue());
addBatchRequest.add("Transportation_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Transportation_group").getValue());
addBatchRequest.add("Loading_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Loading_group").getValue());
addBatchRequest.add("Profit_Center", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Profit_Center").getValue());
addBatchRequest.add("Purchasing_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Purchasing_group").getValue());
addBatchRequest.add("Plant-Specific_Material_Status", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Plant-Specific_Material_Status").getValue());
addBatchRequest.add("Tax_indicator_for_material__Purchasing_", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Tax_indicator_for_material__Purchasing_").getValue());
addBatchRequest.add("Indicator___automatic_purchase_order_allowed_", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Indicator___automatic_purchase_order_allowed_").getValue());
addBatchRequest.add("Purchasing_Value_Key", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Purchasing_Value_Key").getValue());
addBatchRequest.add("Storage_location", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Storage_location").getValue());
addBatchRequest.add("Temperature_conditions_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Temperature_conditions_indicator").getValue());
addBatchRequest.add("Label_type", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Label_type").getValue());
addBatchRequest.add("Label_form", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Label_form").getValue());
addBatchRequest.add("Minimum_remaining_shelf_life", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Minimum_remaining_shelf_life").getValue());
addBatchRequest.add("Total_shelf_life", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Total_shelf_life").getValue());
addBatchRequest.add("Storage_percentage", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Storage_percentage").getValue());
addBatchRequest.add("Documentation_required_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Documentation_required_indicator").getValue());
addBatchRequest.add("QM_in_Procurement_is_Active", AddressXmlNodes[i].selectSingleNode(xPath + "/my:QM_in_Procurement_is_Active").getValue());
addBatchRequest.add("Control_Key_for_Quality_Management_in_Procurement", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Control_Key_for_Quality_Management_in_Procurement").getValue());
addBatchRequest.add("Valuation_Class", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Valuation_Class").getValue());
addBatchRequest.add("Price_control_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_control_indicator").getValue());
addBatchRequest.add("Price_unit", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_unit").getValue());
addBatchRequest.add("Standard_price", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Standard_price").getValue());
addBatchRequest.add("Price_unit_for_valuation_prices_based_on_tax_commercial_law", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_unit_for_valuation_prices_based_on_tax_commercial_law").getValue());
addBatchRequest.add("Material-related_origin", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material-related_origin").getValue());
addBatchRequest.add("Variance_Key", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Variance_Key").getValue());
addBatchRequest.add("Lot_Size_for_Product_Costing", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Lot_Size_for_Product_Costing").getValue());
// Output field has been field with text Retrieving... in Gray color for presentation purpose only
var LogFieldNode = AddressXmlNodes[i].selectSingleNode(xPath + "/my:LogField");
var txtLog = document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId"));
txtLog.value = "Retrieving...";
txtLog.style.color = 'Gray';
// Final web service call parameter
var pl = new SOAPClientParameters();
pl.add("RunParameter", addBatchRequest.toXml());
pl.toXml();
SOAPClient.invoke(WebServer + "/formsservice.svc/basic", "Run", pl, true, CreateIngredient_callBack, i);
}
}
// To display the retrieved result in the proper output fields
function CreateIngredient_callBack(u, xmlresponse, RowNumber) {
var theXmlNode1 = SVFormInternalGetProperXmlNode(SVForms[0]);
var AddressXmlNodes1 = theXmlNode1.selectNodes(RepeatingTableXMLPath);
var xPath = AddressXmlNodes1[RowNumber].getXPath();
var LogFieldNode = AddressXmlNodes1[RowNumber].selectSingleNode(xPath + "/my:LogField");
var txtLog = document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId"));
txtLog.style.color = "";
txtLog.value = "";
if (u == null)
alert("No data retrieved for Row Number " + (RowNumber + 1) + ".");
else {
//Display result in repeating table
if (u.LogField) {
LogFieldNode.setValue(u.LogField);
document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId")).value = u.LogField;
}
}
}
///////////////////// Do not modify below this line ///////////////////////////////
var WsdlResult = null;
//Helping method: To build xml
function SOAPClientParameters() {
var _pl = new Array();
this.add = function (name, value) {
_pl[name] = value;
return _pl;
}
this.toXml = function () {
var xml = "";
for (var p in _pl) {
if (typeof (_pl[p]) != "function")
xml += "<" + p + ">" + _pl[p].toString() + "</" + p + ">";
}
return xml;
}
}
function SOAPClientRepeatingParametersXml(name, values) {
var xml = "";
for (var i = 0; i < values.length; i++) {
xml += "<" + name + ">" + values[i].toString() + "</" + name + ">";
}
return xml;
}
function SOAPClient() { }
SOAPClient.invoke = function (url, method, parameters, async, callback, RowNumber) {
if (async)
SOAPClient._loadWsdl(url, method, parameters, async, callback, RowNumber);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback, RowNumber);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function (url, method, parameters, async, callback, RowNumber) {
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if (wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl, RowNumber);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if (async) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp, RowNumber);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp, RowNumber);
}
SOAPClient._onLoadWsdl = function (url, method, parameters, async, callback, req, RowNumber) {
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl, RowNumber);
}
SOAPClient._sendSoapRequest = function (url, method, parameters, async, callback, wsdl, RowNumber) {
// get namespace
try {
var ns = "http://servername.com/server/";
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
'xmlns:api="http://IPAddress/Integrics/Enswitch/API" ' +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", "http://servername.com/server/I" + ScriptType + "Service/Process(" + WebServiceName + ")");
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if (async) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp, RowNumber);
}
}
xmlHttp.send(sr);
}
catch (ex) { }
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp, RowNumber);
}
SOAPClient._onSendSoapRequest = function (method, async, callback, wsdl, req, RowNumber) {
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
if (nd.length == 0) {
if (req.responseXML.getElementsByTagName("faultcode").length > 0);
alert(req.responseXML.getElementsByTagName("faultstring") [0].childNodes[0].nodeValue);
}
else
o = SOAPClient._soapresult2object(nd[0], wsdl);
if (callback)
callback(o, req.responseXML, RowNumber);
if (!async)
return o;
}
// private: utils
SOAPClient._getElementsByTagName = function (document, tagName) {
try {
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\"" + tagName + "\"]");
}
catch (ex) { }
// old XML parser support
return document.getElementsByTagName(tagName);
}
SOAPClient._soapresult2object = function (node, wsdl) {
return SOAPClient._node2object(node, wsdl);
}
SOAPClient._node2object = function (node, wsdl) {
// null node
if (node == null)
return null;
// text node
if (node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdl);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdl);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdl).toLowerCase().indexOf("arrayof") != -1;
// object node
if (!isarray) {
var obj = null;
if (node.hasChildNodes())
obj = new Object();
for (var i = 0; i < node.childNodes.length; i++) {
var p = SOAPClient._node2object(node.childNodes[i], wsdl);
obj[node.childNodes[i].nodeName] = p;
}
return obj;
}
// list node
else {
// create node ref
var l = new Array();
for (var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdl);
return l;
}
return null;
}
SOAPClient._extractValue = function (node, wsdl) {
var value = node.nodeValue;
switch (SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdl).toLowerCase()) {
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if (value == null)
return null;
else {
value = value + "";
value = value.substring(0, value.lastIndexOf("."));
value = value.replace(/T/gi, " ");
value = value.replace(/-/gi, "/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypeFromWsdl = function (elementname, wsdl) {
var ell = wsdl.getElementsByTagName("s:element"); // IE
if (ell.length == 0)
ell = wsdl.getElementsByTagName("element"); // MOZ
for (var i = 0; i < ell.length; i++) {
if (ell[i].attributes["name"] + "" == "undefined") // IE
{
if (ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("name").nodeValue == elementname && ell[i].attributes.getNamedItem("type") != null)
return ell[i].attributes.getNamedItem("type").nodeValue;
}
else // MOZ
{
if (ell[i].attributes["name"] != null && ell[i].attributes["name"].value == elementname && ell[i].attributes["type"] != null)
return ell[i].attributes["type"].value;
}
}
return "";
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function () {
try {
if (window.XDomainRequest) {
var req = new window.XDomainRequest();
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load",
function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
}
catch (ex) {
try {
if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load",
function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
}
catch (ex) {
try {
// Internet Explorer
if (window.ActiveXObject)
return new ActiveXObject("Msxml2.XMLHTTP"); //ActiveXObject(SOAPClient._getXmlHttpProgID());
} catch (e) {
// Firefox, Opera 8.0+, Safari
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
}
}
SOAPClient._getXmlHttpProgID = function () {
if (SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for (var i = 0; i < progids.length; i++) {
try {
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) { };
}
throw new Error("Could not find an installed XML parser");
}
Thanks in advance for any helpful input.
Cheers
Try & instead of & sign.
Related
Check a json value against a regexp throws a is not a function error
I've a problem with an if statement, where I want to check the value against a regExp. But I get "data[key].name is not a function", how do I go about to fix this issue? document.querySelector('#search').onkeyup = function() { var searchField = document.querySelector('#search').value; var myExp = new RegExp(searchField, "i"); var request = new XMLHttpRequest(); request.open('GET', 'allCountries.json', true); request.onreadystatechange = function() { if ((request.readyState === 4) && (request.status === 200)) { var data = JSON.parse(request.responseText); var output = '<ul class="searchresult">'; for(var key in data) { if(data[key].name(myExp) != -1 || data[key].code(myExp) != -1) { output += '<li>' + data[key].name + ' - ' + data[key].code + '</li>'; } } output += '</ul>'; document.querySelector('#update').innerHTML = output; } }; request.send(); };
If you want to check if a String matches a RegEx pattern, use the String#match() function: Change your if statement to if (data[key].name.match(myExp) || data[key].code.match(myExp)) { var myExp = new RegExp("something.*[23]", "i"); var data = {a:{name:"something1", code:"somethingElse1"}, b:{name:"something2", code:"somethingElse2"}, c:{name:"something3", code:"somethingElse3"}} var output = '<ul class="searchresult">'; for (var key in data) { if (data[key].name.match(myExp) || data[key].code.match(myExp)) { output += '<li>' + data[key].name + ' - ' + data[key].code + '</li>'; } } output += '</ul>'; document.querySelector('#update').innerHTML = output; <div id="update"></div>
If name and code are strings you should test your regex this way: if(myExp.test(data[key].name) || myExp.test(data[key].code))
capturing all dom manipulation events
I'm trying to create a proxy JS so every request to external resource will be proxied like XHR or any other resource. so for XHR request i manage to do it with this code: if(window.XMLHttpRequest) { var XMLHttpRequest = window.XMLHttpRequest; var startTracing = function () { XMLHttpRequest.prototype.uniqueID = function() { // each XMLHttpRequest gets assigned a unique ID and memorizes it // in the "uniqueIDMemo" property if (!this.uniqueIDMemo) { this.uniqueIDMemo = Math.floor(Math.random() * 1000); } return this.uniqueIDMemo; } // backup original "open" function reference XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open; var newOpen = function(method, url, async, user, password) { //console.log(url);//new if (url.includes("somesample")) { //Debug Only /*console.log("[" + this.uniqueID() + "] intercepted open (" + method + " , " + url + " , " + async + " , " + user + " , " + password + ")");*/ urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url); hostname = urlParts[1]; // www.example.com path = urlParts[2]; // /path/to/somwhere proxyprefix = "http://myproxy.com/xhr.php?url=" fullurl = "http://" + hostname + path; rewrittenUrl = proxyprefix + btoa(encodeURIComponent(fullurl)); url = rewrittenUrl; } this.oldOpen(method, url, async, user, password); } XMLHttpRequest.prototype.open = newOpen; // backup original "send" function reference XMLHttpRequest.prototype.oldSend = XMLHttpRequest.prototype.send; var newSend = function(a) { //console.log("[" + this.uniqueID() + "] intercepted send (" + a + ")"); var xhr = this; var onload = function() { /*console.log("[" + xhr.uniqueID() + "] intercepted load: " + xhr.status + " " + xhr.responseText);*/ }; var onerror = function() { /* console.log("[" + xhr.uniqueID() + "] intercepted error: " + xhr.status);*/ }; xhr.addEventListener("load", onload, false); xhr.addEventListener("error", onerror, false); this.oldSend(a); } XMLHttpRequest.prototype.send = newSend; } startTracing(); } else if (window.ActiveXObject) { var ActualActiveXObject = ActiveXObject; var ActiveXObject = function(progid) { var ax = new ActualActiveXObject(progid); if (progid.toLowerCase() == "msxml2.xmlhttp") { var o = { _ax: ax, _status: "fake", responseText: "", responseXml: null, readyState: 0, status: 0, statusText: 0, onReadyStateChange: null }; o._onReadyStateChange = function() { var self = o; return function() { self.readyState = self._ax.readyState; if (self.readyState == 4) { self.responseText = self._ax.responseText; self.responseXml = self._ax.responseXml; self.status = self._ax.status; self.statusText = self._ax.statusText; } if (self.onReadyStateChange) self.onReadyStateChange(); } }(); o.open = function(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword) { /*console.log("intercepted open (" + bstrMethod + " , " + bstrUrl + " , " + varAsync + " , " + bstrUser + " , " + bstrPassword + ")");*/ varAsync = (varAsync !== false); this._ax.onReadyStateChange = this._onReadyStateChange return this._ax.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword); }; o.send = function(varBody) { return this._ax.send(varBody); }; } else var o = ax; return o; } } and its working fine. and because i have got some js that manipulate the dom and adds elements i need to intercept that to. so i started by rewriting appendChild with that code: window.callbackFunc = function(elem, args) { //console.log(elem); for (var key in elem) { if (elem.hasOwnProperty(key) && elem[key].src) { elem[key].src = "http://myptoxy/proxy.php?u=" +encodeURIComponent(elem[key].src); } } } window.f = Element.prototype.appendChild; Element.prototype.appendChild = function() { window.callbackFunc.call(this, arguments); return window.f.apply(this, arguments); }; and thats also working well but i encounter a problem with createlement. some js code on my site creates an iframe with src that i'm unable to intercept with this code: document.createElement = function(create) { return function() { var ret = create.apply(this, arguments); //console.log(ret); for (var key in ret) { if (ret.hasOwnProperty(key) && ret[key].src) { ret[key].src = "http://myproxy.com/proxy.php?u=" + encodeURIComponent(elem[key].src); } } return ret; }; }(document.createElement) I mean I can intercept the creation but the attributes are empty obviously the script adds the attribute after the element creation) I tried to use MutationObserver but with no luck... Any help? Another approach to the entire problem will be great!
How to save the parameters value between functions call?
I'm trying to create a weather app, sending Ajax requests to OpenWeatherMap. I've got an error in w.getWeatherFunc, when I'm giving the function sendRequest the parameter of w.weather and then giving the same parameter to the function displayFunc, which I'm calling next. Here is what I've got in the console: Uncaught TypeError: Cannot read property 'weather' of undefined at displayFunc (weather.js:46) at weather.js:78 How can I fix this and make it work? function Weather () { var w = this; var weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?'; var appid = '&appid=c0a7816b2acba9dbfb70977a1e537369'; var googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='; var googleKey = '&key=AIzaSyBHBjF5lDpw2tSXVJ6A1ra-RKT90ek5bvQ'; w.demo = document.getElementById('demo'); w.place = document.getElementById('place'); w.description = document.getElementById('description'); w.temp = document.getElementById('temp'); w.humidity = document.getElementById('humidity'); w.getWeather = document.getElementById('getWeather'); w.addCityBtn = document.getElementById('addCity'); w.rmCityBtn = document.getElementById('rmCity'); w.icon = document.getElementById('icon'); w.wind = document.getElementById('wind'); w.time = document.getElementById('time'); w.lat = null; w.lon = null; w.cityArray = []; w.weather = null; function sendRequest (url, data) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { data = JSON.parse(request.responseText); console.log(data); return data; } else { console.log(request.status + ': ' + request.statusText); } } } function displayFunc (obj) { console.log('obj ' + obj); w.icon.src = 'http://openweathermap.org/img/w/' + obj.weather[0].icon + '.png'; var timeNow = new Date(); var hours = timeNow.getHours(); var minutes = timeNow.getMinutes() < 10 ? '0' + timeNow.getMinutes() : timeNow.getMinutes(); w.time.innerHTML = hours + ':' + minutes; w.place.innerHTML = 'Place: ' + obj.name; w.description.innerHTML = "Weather: " + obj.weather[0].description; w.temp.innerHTML = "Temperature: " + w.convertToCels(obj.main.temp) + "°C"; w.humidity.innerHTML = "Humidity: " + obj.main.humidity + '%'; w.wind.innerHTML = 'Wind: ' + obj.wind.speed + ' meter/sec'; } w.convertToCels = function(temp) { var tempC = Math.round(temp - 273.15); return tempC; } w.getWeatherFunc = function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(location){ w.lat = location.coords.latitude; w.lon = location.coords.longitude; var url = weatherUrl + 'lat=' + w.lat + '&lon=' + w.lon + appid; var result = sendRequest(url, w.weather); console.log(result); displayFunc(result); }); } else { alert('Browser could not find your current location'); } } w.addCityBtn.onclick = function() { var newCity = prompt('Please insert city', 'Kiev'); var gUrl = googleUrl + newCity + googleKey; var newCityWeather = null; sendRequest(url, newCityWeather); var location = newCityWeather.results[0].geometry.location; var newUrl = weatherUrl + 'lat=' + location.lat + '&lon=' + location.lng + appid; sendRequest(newUrl, w.weather); displayFunc(newCity); w.cityArray.push(newCity); } window.onload = w.getWeatherFunc; setInterval(function() { w.getWeatherFunc(); }, 900000); }
Your ajax return returns into the browsers engine. As its async you need to create a callback: function sendRequest(url,data,callback){ //if the data was received callback(data); } Use like this sendRequest("yoururl",data,function(data){ displayFunc(data); });
The first time you pass the obj to the function it will save it one scope higher. after that, if you don;t pass the object the one you saved earlier will be used. var objBkp; function displayFunc (obj) { if(undefined === obj) obj = objBkp; else objBkp = obj; // rest of code here }
In your sendRequest you are passing only the value of w.weather, not its reference. JavaScript doesn't pass variables by value or by reference, but by sharing. So if you want to give the value to your variable you should do this inside your function sendRequest: request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { w.weather = JSON.parse(request.responseText); console.log(data); return data; } else { console.log(request.status + ': ' + request.statusText); } } Also, if you are using the attributes, you don't have to pass them in the function as arguments. Besides that fact, it would be good if you also create get() and set()
What does the console.log(result); in getWeatherFunc gives you? The problem as I see it is that in the displayFunc the parameter passed is undefined.
nodejs, function jumping to a completely unrelated line for no reason?
So I'm trying to add a command to an already existing project InsomBot to retrieve a League of Legends player's information, I am using lol-api found on npm for this, the only modifications made to this package were to update the API url's as they were outdated and incorrect, my code is below and an image of the issue in a debugger is also below, once the program reaches line 105 it jumps to line 111 for seemingly no reason, perhaps I'm missing a simple indentation error here or I'm not closing something properly, etc. Any help would be appreciated. i.stack.imgur.com/PnDHU.png (Seems I can't post more than 2 links) var cc = require('config-multipaas'), env = require('./env.json'), Discord = require('discord.js'), Imgur = require("imgur-search"), Giphy = require('giphy-wrapper')(env["giphy_key"]), urban = require('urban'), api = require('lol-api'); //lol api.configure("API_KEY_HIDDEN"); var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080 var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1' var config_overrides = { PORT: server_port } var config = cc(config_overrides); var mybot = new Discord.Client(); var isearch = new Imgur(env["imgur_key"]); var termCount = new Map(); var seenURLs = new Map(); mybot.on("message", function (msg) { var message = msg.content; //keywords var giphy = "/giphy "; var imgurKey = "/img "; var hatter = "hater"; var def = "/define "; var commands = "/commands"; var lolstatus = "/lolstatus"; // Reply to direct mentions if (msg.isMentioned(mybot.user)) { mybot.reply(msg, "right back atcha"); return; } // Giphy var giphyIndex = message.indexOf(giphy); if (giphyIndex > -1) { var term = message.substring(giphyIndex + giphy.length).trim().replace(/\s/g, "+"); var count = termCount.get(term) || 0; // console.log("count for term " + term + " is: " + count); termCount.set(term,count+1); Giphy.search(term, 100, count, function (err, data) { if (err) { return; } var items = data.data; var index = Math.floor(Math.random() * items.length / 2.0); // console.log("found " + items.length + " items for " + term); while (index < items.length && seenURLs.get(items[index].url) !== undefined) { index++; } // console.log("using? result number " + index); if (items.length > index) { var item = items[index]; seenURLs.set(item.url, 1); mybot.sendMessage(msg, item.url); } else { var apology = "sorry, I couldn't find any giphys for the term: " + term; mybot.reply(msg, apology); } }); return; } //Imgur var imgurIndex = message.indexOf(imgurKey); if (imgurIndex > -1) { var term = message.substring(imgurIndex + imgurKey.length).trim().replace(/\s/g, "+"); // console.log("searching imgur for term: " + term); isearch.search(term).then(function(results) { // console.log("found results: " + JSON.stringify(results,null,2)); if (results === undefined || results.length === 0) { mybot.reply(msg, "sorry, I couldn't find any imgurs for the term: " + term); return; } var image = results[Math.floor(Math.random() * results.length)]; mybot.sendMessage(msg, "Here's a description of an image: " + image.title + " " + image.description + " " + image.link); }); return; } //lol var lolIndex = message.indexOf(lolstatus); debugger; if (lolIndex > -1) { debugger; var term = message.substring(lolIndex + lolstatus.length).trim().replace(/\s/g, "+"); debugger; api.summonerByName(term, 'na', function(results){ debugger; console.log(results); }); } //Define var defIndex = message.indexOf(def); if (defIndex > -1) { var term = message.substring(defIndex + def.length).trim().replace(/\s/g, "+"); urban(term).first(function(json) { if (json !== undefined) { // console.log("got json from UD: " + JSON.stringify(json,null,2)); var definition = "" + json.word + ": " + json.definition + "\nupvotes: " + json.thumbs_up + " downvotes: " + json.thumbs_down + "\n\nExample: " + json.example; mybot.reply(msg, definition); } else { var apology = "sorry, I couldn't find a definition for: " + term; mybot.reply(msg, apology); } }); } //Hatter if (message === hatter) { mybot.sendMessage(msg, "https://pbs.twimg.com/media/CM5gg9YVAAAVMcn.png"); return; } //Commands if (message === commands) { mybot.sendMessage(msg, "Available commands:[/] giphy | img | define"); return; } }); mybot.login(env["discord_email"], env["discord_pass"]); Line 105 = api.summonerByName(term, 'na', function(results){ Line 111 = var defIndex = message.indexOf(def);
Line 111 contains the next statement after line 105, so it makes perfect sense. api.summonerByName() is an asynchronous method, so its callback (lines 106 and 107) will be called only when there are results available, but the rest of your program will continue to run.
JavaScript variable not changing with XMLHttpRequest
I tried to run this but it doesn't work. It is intended to return a variable assigned inside a function, that was passed as callback to sendRequest(), which is retrieving data from the Internet through XMLHttpRequest asynchronously. Can anyone tell me why this is not working and always returning ""? function sendRequest(requestCode, args, callback){ var req = requestEngineUrl + "?req=" + requestCode + ";" + args; var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4) { if(callback != null){ callback(xmlHttp.responseText); } } }; xmlHttp.open("GET", req, true); xmlHttp.send(null); } this.assembleProcess = function(){ if(!isNull(this.id) && !isNull(this.titles)){ var titles = this.titles; var id = this.id; c = ""; sendRequest('304', id, function(result){ var res = result.split("/"); var title = res[0]; var possibilities = res[1]; var fcontent = title + '<br><div>'; if(titles.length != possibilities){ console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities"); } for(i = 0; i < possibilities; i++){ fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>'; } fcontent += '</div>'; c = fcontent; }); return c; }
As an XMLHttpRequest is async, you should write an async function for that matter, like this this.assembleProcess = function(callback){ if(!isNull(this.id) && !isNull(this.titles)){ var titles = this.titles; var id = this.id; c = ""; sendRequest('304', id, function(result){ var res = result.split("/"); var title = res[0]; var possibilities = res[1]; var fcontent = title + '<br><div>'; if(titles.length != possibilities){ console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities"); } for(i = 0; i < possibilities; i++){ fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>'; } fcontent += '</div>'; c = fcontent; callback(c) }); } and then, instead of using this.assembleProcess as a function with a result, you should pass a function as parameter: Instead of console.log(this.assembleProcess); do this this.assembleProcess(function(c){console.log(c)});