Getting Object Expected Error in Server Side Javascript Code - javascript

I am getting an error stating that an object is expected in the below code. The error is:
Object Expected: this.regionalRankings[worldRegion][rankType] = this.getRankings(rankType, this.regionalRankingKey[worldRegion]);
Declarations...
this.regions = {};
this.regions = ["US", "Europe", "Asia"];
this.regionalRankingKey = ["SP500", "GBE", "CNG"]; //this is the ranking model key for pulling up the rankings object.
this.rankingTypes = ["gainers", "losers", "actives"];
this.regionalRankings = {};
this.rankingWSODIssues = [];
marketSummary_data.prototype.initRankingsNew = function(){
for(var worldRegion in this.regions){
for (var rankType in this.rankingTypes){
//this is the line getting the error.
this.regionalRankings[worldRegion][rankType] = this.getRankings(rankType, this.regionalRankingKey[worldRegion]);
for(var i = 0; i < 5; i++){
this.rankingWSODIssues.push(this.regionalRankings[worldRegion][rankType].value("Result[0].Row[" + i + "].WSODIssue"));
}
}
}
for(var item in this.rankingWSODIssues){
Response.Write("<p>" + item + ": " + rankingWSODIssues[item] + "</p>");
}
}
the function this.getRankings returns an object.
marketSummary_data.prototype.getRankings = function(rankingType, rankingSet){
//ranking types Epctchg+ (pct gainers)
//Epctchg- (pct losers)
//Edollar+ (net gainers)
//Edollar- (net losers)
//Evol+ (highest volume)
//rankingSets
if (rankingType == "gainers"){
rankingType = "Epctchg+";
}
if (rankingType == "losers"){
rankingType = "Epctchg-";
}
if (rankingType == "actives"){
rankingType = "Evol+";
}
var rankings = User.CreateObject("WIT.Rankings.1")
rankings.SetVariableName("Rankings")
rankings.SetInput("Ranking.RT", 0)
rankings.SetInput("Ranking.Type", rankingType)
rankings.SetInput("Ranking.Set", rankingSet)
rankings.SetInput("Ranking.Rows", 5)
rankings.SetInput("Ranking.Symbolset", "BridgeStreet");
rankings.SetInput("Ranking.MinPrice", 0); // only want stocks trading higher> 0
rankings.Retrieve();
return rankings;
}
Any ideas on what I am doing wrong here?

The problem is that this.regionalRankings[worldRegion][rankType] requires that this.regionalRankings[worldRegion] be something, however this.regionalRankings is an empty object, so an "Object is Required."
I think what you intended to do is:
for(var worldRegion in this.regions){
this.regionalRankings[worldRegion] = {}; // Make it into an object.
for (var rankType in this.rankingTypes){
this.regionalRankings[worldRegion][rankType] = ...
}
}

Related

how to use dynamic variable in update.js shopify

I want yo use test variable in update.js but it shows error when I use as variable but when I pass this value directly it works
can someone please tell me how can use dynamic variable to change quantity of existing products in cart
I have updated my code It will allow user to add only 5 items more than 5 items will be removed It will create string which will look like this
32082238341235:0,39470423048307:0,32164693278835:0,32164693835891:1
and finally the all IDs and qunatity will be updated by update.js
I have got error in last step its shows
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
when i try to update all products
jQuery.getJSON('/cart.js', function(cart) {
var items_new = cart.items;
var count = 0;
count = cart.item_count;
var item_to_remove = count - 5;
if (count > 5) {
var item_to_remove = count - 5;
var combine = ""
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove
var data_multiple = c_id + ":" + q + ",";
debugger;
count = count - item_to_remove;
console.log(data_multiple);
var combine = combine + data_multiple;
} else {
var data_single = c_id + ":" + 0 + ",";
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity
console.log(data_single)
var combine = combine + data_single;
}
}
}
console.log(combine.slice(0, -1));
var test = combine.slice(0, -1);
console.log({
updates: {
test
}
});
jQuery.post('/cart/update.js', {
updates: {
test
}
});
}
t._rerenderCart()
}
t.sidebarDrawer.open()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to store test as an object within parentheses {} and then pass to updates by using the spread ... operator.
var test = {39470423048307 : 0, 32164693278835 : 0, 32164693835891 : 1};
console.log({updates: {...test}});
jQuery.post('/cart/update.js', {updates:{...test}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your updated code, you are passing a string to updates rather than an object. You should create an object from the data inside the for loop and pass that object to updates. See lines with // CHANGE HERE:
...
var combine = {};
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove;
// CHANGE HERE
combine[c_id] = q;
count = count - item_to_remove;
} else {
// CHANGE HERE
combine[c_id] = 0;
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity;
}
console.log(combine);
}
}
// CHANGE HERE
var test = combine;
console.log({
updates: test
});
jQuery.post('/cart/update.js', {
updates: test
});
...

Cannot read property 'split' of null

I cannot display all the results because on the following channel there is no image and therefore I have the following message
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos.split('$');
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
The one index does not have a value for the property. It is null, so you need to check to see if it is null before you try to use split on it. A simple truthy check will work in this case.
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
With it in place:
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
console.log(this);
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="target"></div>
split is a method on string objects, which will be called on an actual string's reference.
So in your case, the split is not being called on a string, and the error message clearly states that we are using split over a null object. So make sure the object you are working on is an actual string, and work on it accordingly.
split mdn

Looping error in Javascript with eventHandler

I have the following Javascript code within and HTML page. Its function is to display elements on the form based on the user pressing a + button and if the element is not needed then it removes it via the user pressing the - button. Currently its throwing an error "TypeError: docs[n]" is undefined after the following sequence of events:
Select button to add elements
Remove elements not needed
Add elements back (Error Thrown)
Any help would be most appreciated
`<script language="JavaScript">`
var idx = 0;
var d;
//Make getElementsByClassName work for all of IE revs
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
function add_fields(e) {
// for some reason, adding the new fields wipes out existing values, so save and restore
var docs = document.getElementsByClassName("doc");
var revs = document.getElementsByClassName("rev");
++idx;
/* console.log("test " + idx); */
var saveDocs = new Array(idx);
var saveRevs = new Array(idx);
for (n=0; n < idx; n++) {
saveDocs[n] = docs[n].value; **//Error is thrown here**
saveRevs[n] = revs[n].value;
}
node = document.getElementById("content");
theNewRow = document.createElement("tr");
theNewCell = theNewRow.insertCell(0);
theNewCell.innerHTML = "Approver Name";
theNewCell.setAttribute("style","font-size: 12pt");
theNewCell1 = theNewRow.insertCell(1);
theNewCell1.innerHTML = "<input type='text' class='doc' style='width:180px;' id='docNum0'/>";
theNewCell1.setAttribute("style","padding-left: 10px");
theNewCell2 = theNewRow.insertCell(2);
theNewCell2.innerHTML = "Approver Email";
theNewCell2.setAttribute("style","font-size: 12pt");
theNewCell2.setAttribute("style","padding-left: 10px");
theNewCell3 = theNewRow.insertCell(3);
theNewCell3.innerHTML = "<input type='text' class='rev' style='width:180px;' id='rev0'/> <input class='minusThing' type='button' style='font-size:10px' value='- '/>";
theNewCell3.setAttribute("style","padding-left: 0px");
node.appendChild( theNewRow );
// restore old arrays and add the id tags to the fields just added
docs = document.getElementsByClassName("doc");
revs = document.getElementsByClassName("rev");
for (n=0; n < idx; n++) {
docs[n].value = saveDocs[n];
revs[n].value = saveRevs[n];
}
docs[idx].id = "docNum" + idx;
revs[idx].id = "rev" + idx;
}
//for Loop the entries
function myfunction() {
alert('Inside Function')
var values = "";
for (n=0; n <= idx; n++)
{
var doc = document.getElementById("docNum"+n).value;
var rev = document.getElementById("rev"+n).value;
//alert(doc+rev);
//Call VbScript Sub and pass value
PassValues(doc,rev);
```
If you've removed all the docs, document.getElementsByClassName("doc"); is going to return an empty array. If you're incrementing idx before your loop, the loop will execute once and try to access docs[0], which is undefined.

JSON input string error using $.ajax

My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);

Undefined is returned from appended array

I currently POST to my script:
process : edit
r1_person : 00008
r2_person : 00009
persons : 2
Which my script accepts:
if (process == 'edit') {
var persons_array = [];
for (i = 0; i < persons; i++) {
var test_push = pnvl(request.getParameter('r' + i + '_person'))
persons_array.push(test_push);
response.write(persons_array[i] + '\n');
}
}
I get back:
undefined
undefined
Where am I going wrong?
EDIT:
Solution: response.write() will not return correctly inside a for loop.
Try this:
pnvl(request.getParameter(eval('r' + i + '_person')))
you iterate from 0 to 1, you want this:
for(i = 1; i <= persons; i++)

Categories

Resources