Ethereum For Beginners

Interact with smart contract from frontend

This is lesson 6 of Ethereum development beginner guide and this lesson shows how to interact with smart contracts deployed on blockchain. To go over detail steps, you can watch the below video.

To interact with smart contract deployed on blockchain we need to have web3.eth module that helps us to interact with smart contracts. We follow below high level in this lesson.

  1. Create a project in Visual Studio Code
  2. Install Web3 under that project
  3. Create HTML page
  4. Use web3 to connect to blockchain and interact with smart contracts

Let's go over these steps one by one.

Create a project

First create a folder using below command.

mkdir studentSample

Once you run this command, it create a folder, now go inside that folder and run below command.

npm init

Once you run this command, it prompts for few questions that you need to answer or simply press enter. This create package.json file under that directory and it look like below.

{ "name": "studentSample", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }

Install Web3

Now we install web3 under the project folder, for that run  below command

npm install ethereum/web3.js --save

This command install web3 module in that project folder.

Create HTML 

Now open Visual Studio Code and open that studentSample folder. Now next step is build frontend from where we interact with smart contract.

Instead of creating that HTML page, you can download the project from studentSample.

Interact with Smart Contract

As mentioned earlier, web3 module is used to interact with smart contract so in that HTML page, web3 provider is used first to connect to blockchain using below code and then connection made to smart contract using the ABI.

if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545")); }

 

var StudentContract = web3.eth.contract(abi);

var student = StudentContract.at('0xf52f6a71eae0dc9a10b4a73d4653f9b754e9e0b4');

Then to access smart contract function setStudentDetails you need to write below code as shown below.

$("#button").click(function() { student.setStudentDetails($("#studentName").val(), $("#studentAge").val()); });

 

 

Download the whole project from studentSample

Lesson Intro Video

Please login to get access to the quiz
Deploy smart contracts to TestNet Blockchain (Prev Lesson)
Back to Ethereum For Beginners
Inquire Now
close slider