I am completely stuck

Hi @Adept

When you ask an input using prompt, the type of the input you get is string.
This makes a huge difference for you if condition:

(busstop2 + busstop1 < 30)

Because busstop1 and busstop2 are strings, the plus (+) operator adds them:
10 + 10 = 1010

Your if condition will be (1010 < 30) and not (20 < 30).

You have to parse the two strings to integers as follow:

if (parseInt(busstop2) + parseInt(busstop1) < 30) {
console.log ("This many people went on to stop two: ", (busstop2));
}
else {
console.log (“Buss is full”);
}

Keep in mind that you can debug your code easily by using console.log() to inspect your variables.

Happy coding,
Dani

Hey @Louwrens

PowerShell is telling you that li is not a command.
What are you trying to do?

In order to verify if node is installed, you can run the command node -v.

Regards,
Dani

I am trying to following the instructions on th JS course under - Javascript in Terminal - NodeJS- I installed node.js, then ivan does cd, that works, but li and npm does not. Ivan says when you do npm and “this” comes up it means it is fine and node.js is installed, and he goes on, but mine gives this error and not what “this” was that he was referring to.

Hi @Louwrens

Can you please run the command node -v and post the result here?

thanks,
Dani

PS D:\Scriptz\myNodeJs> node -v
v15.10.0

Hi @Louwrens

From your screenshot above I see that you are trying to run the command li.
If you are trying to list the elements inside a folder, run command ls.
Video.

Regarding node, I see that you are inside the disk D:, for the sake of testing can you try to cd into a folder in your disk C: and run npm.

Plese post a screenshot once done.

Cheers,
Dani

Thanks Dan!

it’s working now

You are welcome @Louwrens

I guess it is because you have installed node in the C drive, but you were trying to run it in D :slight_smile:

Happy coding,
Dani

Many thankssss the problem it is sort out :slightly_smiling_face:

1 Like

alt is not working to add description for the picture. Please see below, I am not sure what it is I am doing wrong Thanks

<img src=“https://www.humanesociety.org/sites/default/files/styles/1240x698/public/2018/08/kitten-440379.jpg?h=c8d00152&itok=1fdekAh2"alt="supercat"width="150” height=“150”/>

For future readers: I could solve this by loop an async function like this:

Looping Async Function to get complete array data from public array (SOLVED)
async function getAllCands() {                          //First declare your getWhicheverArrayYouNeed function as **async**
  const candsLength = await voteApp.methods.candLength().call(); //Then you need length of your array
  for (let i = 0; i < candsLength; i++){   //then you loop for the length of your array
    candsNames.push(                         //and push all results into a new array inside your .js
    await voteApp.methods.candidates(i).call().then(result => {  //access your **public** array through the getter function and make it **await** !!
        return [result[0]];
      })
    )
    candsIds.push(i);   //Here I keep track of the entries in another array by pushing i (nr. of iteration)

  }
  $("#name0_out").text(web3.utils.toUtf8(candsNames[1].toString()));  //Converts array entry to string and prints it to element name0_out
  printCands();   //This will print all entries from the array to the website
  console.log(candsNames);
  console.log(candsIds);
}

async function printCands(){   //this function will dynamically print all retrieved elements from the getYourArray Function
  const candsLength = await voteApp.methods.candLength().call();   //You need length of array again
  for (var i = 0; i < candsLength; i++){    //Creates HTML elements for each element in array
   $('<input type="button" id="Candidate" value="Vote For" onclick="setID(this.id)"></input>' ).click(castVote).appendTo('.CandsOut');   //appendTo will do the magick and make it visible in the document
    $('<div class="candsOut" id="CandsListing" />').text("ID: " + candsIds[i] + ": " + web3.utils.toUtf8(candsNames[i].toString())).appendTo('.CandsOut');
    document.getElementById("Candidate").value = "Vote for " + web3.utils.toUtf8(candsNames[i].toString()); //Sets value for the button "Candidate" so it will say Vote For Candidate
    document.getElementById("Candidate").name = parseInt(candsIds[i]);  //Sets name of element to id, this is an experiment
    document.getElementById("Candidate").id = i;  //Sets button id to id candidate
  }
}
Problem: get all entries from public array

Ok, here is my struggle. I want to print all candidates from a public array into the HTML file using javascript. So I tried to put the async function getCandidates into a loop (forloop, also tried while loop) - without any luck. How would one achieve this? I looked at many sources on the web but could not implement something that works. I imagine something like this (pseudocode):

function getCandidates(){
for(var i = 0; i <= length; i++){  //length is set by getArraylength function
  voteApp.methods.candidates(i).call().then(function(res){
        candsNames.push(res.name);
        candsIds.push(i);
        console.log(candsNames[i]);
        console.log(candsIds[i]);
  })
}
format problem of we3.utils.toAscii (SOLVE)

The solution is: web3.utils.toUtf8(YourVariable.toString());

Also, how can I make the web3.utils.toAscii format the string output “right”? As you can see in the picture output name comes with symbols…

@thecil @dan-i @filip
toAsciiFormat

I am unable to replicate your issue.
Post your project on GitHub and share the repo, I will deploy and check

1 Like

REPO
So the problem right now really leaves me puzzled, because the contract works fine in the console and in remix and also Unit tests pass. But the frontend will not work:
ErrorRPC
And when calling the approveVoters function I get this:
ErrorRPC

I suspect that the code is right, but there is some issue with the network ? I tried to run it on truffle develop as well as ganache.
Any help much appreciated @dan-i, @Malik, @filip, @thecil. I guess you guys are very busy as well. So if you find time, this is my first project I pushed so far on my own and I really learned a lot, from passing values between functions and languages to generating HTML from within javascript and looping async functions to retrieve data from public arrays. But when googling this errors I find very different opinions and solutions. Some say it is a bug in the client (ganache) and that problems with nonces are not easily solvable and so on… I hope to get your feedback on this. Thanks :slight_smile:

Invalid Number SOLVED

This is fixed by:

function setID(id){
  console.log(id);
  voteID = id;
  //voteID = BigInt(parseInt(id));

  console.log(voteID);
}

and passing the id to the vote function .

UPDATE 16-03, 11pm

@dan-i, so the Repository is updated once again. I rearranged the voting process a bit so that each candidate will have its own button and the user can vote for the candidate directly by pressing the respective button. The problem now still is, how do I pass the value of the vote to the vote function in the contract.

At the moment I get his err:

web3.min.js:1 Uncaught (in promise) Error: invalid number value (arg="candidate", coderType="uint256", value=null)
    at Object.n [as throwError] (web3.min.js:1)
    at t.encode (web3.min.js:1)
    at web3.min.js:1
    at Array.forEach (<anonymous>)
    at N (web3.min.js:1)
    at t.encode (web3.min.js:1)
    at e.encode (web3.min.js:1)
    at i.encodeParameters (web3.min.js:1)
    at web3.min.js:1
    at Array.map (<anonymous>)

If you could give me a hint, I would be very grateful.

:pray:

old

UPDATE:
@dan-i, I could solve it!! The Repository is updated. The solution was this:

How to get array values from smart contract and printing them to HTML by looping a getter function async!
async function getAllCands() {
  const candsLength = await voteApp.methods.candLength().call();
  for (let i = 0; i < candsLength; i++){
    candsNames.push(
    await voteApp.methods.candidates(i).call().then(result => {
        return [result[0]];
      })
    )
    candsIds.push(i);

  }
  $("#name0_out").text(web3.utils.toUtf8(candsNames[1].toString()));
  printCands();
  console.log(candsNames);
  console.log(candsIds);
}

async function printCands(){
  const candsLength = await voteApp.methods.candLength().call();
  for (var i = 0; i < candsLength; i++){
    $('<div class="candsOut" />').text("ID: " + candsIds[i] + ": " + web3.utils.toUtf8(candsNames[i].toString())).appendTo('.CandsOut');
  }
}

But if you still want to look into the code, I would be happy to get some help with the “Cast Vote” function. Atm it is throwing this error:

error message Vote function main.js
inpage.js:1 MetaMask - RPC Error: Error: [ethjs-query] while formatting outputs from RPC '{"value":{"code":-32603,"data":{"message":"VM Exception while processing transaction: revert","code":-32000,"data":{"0xbdefcea26f675f626bb40f3815376bb8979c652f9e240492701d13a88d55e17f":{"error":"revert","program_counter":16,"return":"0x"},"stack":"RuntimeError: VM Exception while processing transaction: revert\n    at Function.RuntimeError.fromResults (C:\\Users\\sound\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\node_modules\\ganache-core\\lib\\utils\\runtimeerror.js:94:1)\n    at BlockchainDouble.processBlock (C:\\Users\\sound\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\node_modules\\ganache-core\\lib\\blockchain_double.js:627:1)\n    at runMicrotasks (<anonymous>)\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)","name":"RuntimeError"}}}}' {code: -32603, message: "Error: [ethjs-query] while formatting outputs from…/task_queues.js:93:5)","name":"RuntimeError"}}}}'"}
(anonymous) @ inpage.js:1
(anonymous) @ inpage.js:17
_runReturnHandlers @ inpage.js:17
_processRequest @ inpage.js:17
async function (async)
_processRequest @ inpage.js:17
_handle @ inpage.js:17
handle @ inpage.js:17
_rpcRequest @ inpage.js:1
sendAsync @ inpage.js:1
s.send @ web3.min.js:1
n @ web3.min.js:1
(anonymous) @ web3.min.js:1
u @ web3.min.js:1
(anonymous) @ web3.min.js:1
_handle @ inpage.js:17
async function (async)
_handle @ inpage.js:17
handle @ inpage.js:17
_rpcRequest @ inpage.js:1
sendAsync @ inpage.js:1
s.send @ web3.min.js:1
n @ web3.min.js:1
t @ web3.min.js:1
t @ web3.min.js:1
o._executeMethod @ web3.min.js:1
castVote @ main.js:24
dispatch @ jquery-3.4.1.min.js:2
v.handle @ jquery-3.4.1.min.js:2
main.js:34 Uncaught (in promise) {code: -32603, message: "Error: [ethjs-query] while formatting outputs from…/task_queues.js:93:5)","name":"RuntimeError"}}}}'", stack: "Error: Error: [ethjs-query] while formatting outpu…/task_queues.js:93:5)","name":"RuntimeError"}}}}'"}

:pray:
Repository

I could solve the formatting issue with using web3.utils.toUtf8 instead of toAscii,
The issue with looping an async function call still remains.

:pray:

I am executing a code in lesson 17 of JS programming course and am following along with this practicular video.

I am executing a code that should be false but its showing as true which is the opposite of what’s happening with the instructor in the video I am confused why. Example below:

var a = “true”;
undefined
var b = “true”;
undefined
var c = “false”;
undefined
var d = “false”;
undefined
if( a && c){ alert(“true!”); }

When I execute this code it should be false and the alert shouldn’t pop up but the alert is still popping up on my screen after I enter it.

1 Like

@isaactaylor1
The issue here is that you are initalizing the variables as type string, because you write var a = "true";
By using " " your variable will be of type string, which will always be considered true by JavaScript. Try this instead:

var a = true;
var b = true;
var c = false;
var d = false;
if(a&&c){alert("true!");}

This should not alert anything.

If you initialize the variable without " ", JavaScript will interpret the variable as type bool, which can be either true or false.

Then try

if(a){alert("true");}

This will alert true.

Also try if(a | c ){alert(“TRUE”);}

This will also alert true, because one of them is true.

And:

if(!c){alert("C IS FALSE");}

This will alert because C is false…
I hope this helps

1 Like

This helps, thank you for all of this information.

1 Like

You are welcome. Reach out any time if you have any questions

1 Like

JQuery in Atom code editor.

Hi there everyone.
I want to ask you, if someone here have sometimes experienced some issue with connecting the JavaScript into a Html file you are working on, in the Atom code editor?

At the moment, I’m following Ivan on the Dynamic List Assignment, but I do have an issue connecting the JQuery library in the Atom editor, when I paste the <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> into the HTML Head.

The code line will become just gray, like it has been commented out, and therefor the JQuery doesn’t work.
Sometimes other HTML tags even become gray as well if they are close to the SCRIPT tag, but by keep it few lines away the HTML tags will usually become normal again.

Just wanted to put this issue out here if someone might have some magic trick up their sleeves that might solve this issue :smiley:

Thanks is advance,
Bjarni

JQuery issue

1 Like

…seems to work now, but Script text still gray though.

1 Like

Thats a Visual bug from Atom, its weird and there is no logic explenation for it some times (because you have the syntax highlighted and file folder properly). Nothing to worry that much about to be honest.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like