Contract Value Return – How to call contract function with address and ABI to return value to frontend

frontendgo-ethereumsolidityweb3js

I've deployed the following contract to Ethereum testnet.

contract demo {
  string public name = "someString"; 

  function returnValue() constant returns (string){ 
      return name;    
  }
}

I am trying to retrieve the contract's string and this won't work

var contract = web3.eth.contract(contractAddress, abi); //contractAddress+abi known
console.log(contract.returnValue);

returns undefined

If I use this code:

var asdf = web3.eth.contract(abi).at(contractAddress);
alert(asdf.returnValue);

I get `function(){[native code]}
How can i get the string "name" from my solidity contract to my javascript? Thank you

Best Answer

Try this:

var contract = web3.eth.contract(abiArray).at(contractAddress);
contract.returnValue.call().then(function(v) {
    var strName= v.toString();
    console.log("Name: "+ strName);   
});

This is how I do using truffle:

import demo_artifacts from './../../build/contracts/demo.json';  
var Demo = contract(demo_artifacts);

window.getValue=function(){  
    Demo.deployed().then(function(contractInstance) {  
        contractInstance.returnValue.call().then(function(v) {  
            var strName= v.toString();  
            console.log("Name: "+ strName);
        });    
    });  
}    
window.getValue();  

Try this one:

var abiDef = "(provide the abi)";   
var contractAddress = "(provide the contract address)";  
var objWeb3 = new Web3(new
Web3.providers.HttpProvider("http://localhost:8545"));   
var democontract = objWeb3.eth.contract( JSON.parse(abiDef)).at(contractAddress);  
var callData=democontract.returnValue.call();
console.log(callData); // Printed: BigNumber {s: 1, e: 3, c: Array[1]}  
console.log(callData.c[0]); // Printed: the value in my case 1000