(Part 4)Tutorial On SteemConnect JS Submit A New Post Using @steemconnect pt4

in #utopian-io6 years ago

Repository

https://github.com/igormuba/steemhere

What Will I Learn?

You have, previously, learned how to sign in an user and save his token on the cache so we can work with it, now we will learn how to

  • Use the api.comment function from the SteemConnect JavaScript API
  • Add fields for user to input title, body and tags
  • Manipulate the data from the fields to match the data structure required to post
  • Publish the transaction with all the data of the post sending effectively the post to the blockchain

This tutorials are intended to be very beginner friendly, ideally if I can make it simple enough so that you can copy and paste your way into building your own Steem dapp, then I was successful!

Requirements

If you just want to see how posts can be made with the SteemConnect API, this post alone will work, if you plan to learn from scratch, please, read the former tutorials I have posted before

  • Previous tutorials (parts 1 to 3)
  • Basic JSON knowledge
  • Basic JavaScript and HTML
  • A Steem account with enough RC to post
  • A SteemConnect app to use their API

Difficulty

  • Intermediate

Tutorial Contents

Creating the fields for the post

I am not going to use CSS nor make things fancy in this tutorial to keep things simple.
I am supposing you have followed the previous 2 tutorials, it mandatory to be logged into SteemConnect at this point, so if you are not, scroll all the way down on this post, in the end there are links to the previous classes on how to do it.
Just like this class they are simple and copy and paste friendly so you can be back here in just a few minutes.

Let us break down what are the 3 fields a post needs:

  • Title
  • Body
  • Tags
  • Post button

Though, very soon in this tutorial you will realize that the API require more arguments than that, we will work on the other data by manipulating properly the data from only those 3 fields!

Starting by the basic, that is, creating the input fields!

Start by breaking those poor lines twice just to put the form below the username and profile picture, if you have followed the

 <br>
<br>

Now, below that

(html comment removed:  This is a comment)
    Title <input type="text" id="title"><br> (html comment removed:  The title of the post)
    Content <textarea id="content"></textarea><br> (html comment removed:  The content itself for the post)
    Tags <input type = "text" id="tags"><br> (html comment removed:  The tags for the post)
    <input type="button" value="Post It!" onclick="submitPost()"> (html comment removed: this button will do all the hardwork by calling the function submitPost() we will define right below)

Notice that every field MUST have an unique ID, and the button must have a onclick function to be called when it is clicked. For now, name it inside the button element and right after we will create that function.

Now we go to out JavaScript file, in my case named myscript.js, there we will create a function that will be called when we press the button, command to submit a post is this

//this is just copy and paste from the steemconnect documentation
//https://github.com/steemit/steemconnect.js?files=1
api.comment(parentAuthor, parentPermlink, author, permlink, title, body, jsonMetadata, function (err, res) {
  console.log(err, res)
});

And I know this looks intimidating, it took me a while to understand it, mainly how the jsonMetadata should be formatted, but here I will break everything for you so you can work you way much easier than I did!

On the HTML above we have chosen the name submitPost for the function, now, inside the JavaScript let's create that function, shall we? I am creating it on the very end of the file, so any other variable we might wanna use we can grab, hope this makes sense to you

function submitPost(){
  var allTags = document.getElementById("tags").value; //grabs the tabs field and put to the variable allTags
  allTags = allTags.split(" "); //turns the allTags into an array with all the tags beautifully separated
  
  var parentPermlink=allTags[0]; //sets the main tag (parentPermlink) as the first tag
  var author=document.getElementById("username").innerHTML; //get the username from the logged user
  var title=document.getElementById("title").value; //DOM to grab title from HTML
  var permlink=title.replace(/ /g, "-"); //nice little trick to change the spaces for dashes for the permlink
permlink = permlink.toLowerCase(); //lowercase the permlink to avoid annoying errors (I know it too well)
//notice there is a space between the slashes!!! this changes all spaces to dashes
  var body=document.getElementById("content").value; //DOM to grab the content itself of the post
var jsonMetadata; //just defining this for future use

  api.comment("", parentPermlink, author, permlink, title, body, jsonMetadata, function (err, res) {
  console.log(err, res)
});
}

But still, this won't work, check below first what each of those fields do, then we will format everything so we can generate a transaction and broadcast it!

Preparing the content to be fed into the submitPost function

When the button is clicked it will call submitPost, but as it is it will do nothing but throw errors at you. So allow me to help you out on this.

You see, here are the arguments we must pass to api.comment

  • parentAuthor is the author of the parent post, in this case, I have changed it for "", since we are creating a post, not a comment
  • parentPermlink is the main tag, so we have created an array with the tags and the first tag became the main one
  • author is the name of the user that is posting, we have grabbed it from the HTML (assuming we are logged in from the previous classes)
  • permlink is the link to the post, we are using the parrent of replacing the spaces with -
  • title the title of the post, a simple DOM manipulation will provide us this
  • body the content itself of the post, again, we will use DOM manipulation to fill it
  • jsonMetadata in this example we will put the tags here, in other case, like Steem Monsters, this gives you a huge variaty of possibilities!!!

The function is the end is just the callback function, will be helpful for us to get feedback of errors.

Now, the kinda hard part is the jsonMetadata, I have grabbed a random post to copy the tag so you can see how it should look like, if you want to see the metadata from posts, do the following:

Spot the post on steemit.com you want to see the jsonMetada tags, in this case, I am grabbing it from my last post about my witness server and campaign update

On the URL replace it from steemit.com to d so it becomes steemd.com
before

https://steemit.com/witness-category/@igormuba/igormuba-witness-update-new-projects-backup-server-bringing-new-users-and-curation

after

https://steemd.com/witness-category/@igormuba/igormuba-witness-update-new-projects-backup-server-bringing-new-users-and-curation

You will see this complicated page

but what we care are the tags

And this is the data structure for the tags

{"tags":["witness-category","witness-update","witness","minnowsupportproject","minnowsupport"]}

So, let us use a little bit of our beloved JavaScript to take care of that for us

var tagsMetadata='{"tags":['; //this is the same for all tags, so it is just a static string
  for (var i = 0; i<allTags.length; i++){ //for each tag
    tagsMetadata+='"'+allTags[i]+'"'; //we will add it between double quotes to tagsMetadata
    if (i+1<allTags.length){ //if this is not the last tag
      tagsMetadata+=",";// we add a coma and repeat
    }
  }
  tagsMetadata+="]}"; //another static string that is the same for all strings

jsonMetadata=JSON.parse(tagsMetadata); //use the JSON parser to turn it indeed to a JSON object

There we go, nothing too hard so far, it is really just a bit boring getting the data structure right, trust me, I had a bit of a headache because one character out of place and there goes the Metadata all broken. And since this is supposed to be a CTRL+C and CTRL+V friendly tutorial as my goal is to make people limited only by their creativity, not by technical skills, the code about is just copied and pasted and you will have the data structure right, but I recommend you learning a bit about JSON and strings.

So, make sure it looks similar to this in the end, we have already went through all this code in a breeze, didn't we? look how beautiful the final work is

function submitPost(){
  var allTags = document.getElementById("tags").value;

  allTags = allTags.split(" ");


  var parentPermlink=allTags[0];
  var author=document.getElementById("username").innerHTML;
  console.log("username"+author);
  var title=document.getElementById("title").value;
  console.log("title"+title);
  var permlink=title.replace(/ /g, "-");
permlink = permlink.toLowerCase();
  console.log("permlink"+permlink);
  var body=document.getElementById("content").value;
  console.log("body"+body);


  var tagsMetadata='{"tags":[';
  for (var i = 0; i<allTags.length; i++){
    tagsMetadata+='"'+allTags[i]+'"';
    if (i+1<allTags.length){
      tagsMetadata+=",";
    }
  }
  tagsMetadata+="]}";
  console.log("tagsmetadata"+tagsMetadata);
  var jsonMetadata=JSON.parse(tagsMetadata);
  console.log("jsonmetadata"+jsonMetadata);

  api.comment("", parentPermlink, author, permlink, title, body, jsonMetadata, function (err, res) {
  console.log(err, res)


});
}

Go ahead and do your testing.
Fill the title, content and tags. I have succesfully make a post using this.
Do one too and tag me there @igormuba so I can see your work (I am using @partiko so I can see when you tag me)
and leave a comment here with a link to the post you made just in case I don't get the tag notification

Curriculum

Include a list of related tutorials you have already shared on Utopian that make up a Course Curriculum, if applicable.

Proof of Work Done

Final myscript.js
https://github.com/igormuba/steemhere/blob/class4/js/myscript.js

Final index.html
https://github.com/igormuba/steemhere/blob/class4/index.html

Hey, I am Witness, did you know?

To vote for me, go to https://steemit.com/~witnesses

(note, it is /~witnesses, not /witness)
Scroll all the way down to "If you would like to vote for a witness outside of the top 100, enter the account name below to cast a vote."

type igormuba and click vote

Sort:  

Thank you for your contribution. Below is our feedback:

  • I liked how you are approaching these tutorials in a simplistic and easy to follow approach.
  • The topic is a bit too simple, and posting to Steem via Steemconnect is already documented here, although i liked your approach and how detailed your went into making this tutorial, and you following this via a complete series. My advise though is to personalize those tutorials a bit further, and include additional content inside each tutorial.
  • I had a question, why are you loading JS scripts in the body and not in the head? myscript.js and steemconnect?

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Hi, first, thank you very very much for the detailed feedback, thanks to such replies I believe I have improved from the first tutorial but of course we van always do better.
Regarding the second and third point, at the moment I am introducing the basics, on the former class I have coveref a bit more topics but I became too big, also, the scripts are on the body because I didn't thought much before adding them haha
since it is the basics I knew it wouldn't affect the behavior, but thank you for noticing, I will improve the good practices and consider every comment for the next tutorial

Posted using Partiko Android

Thank you for your review, @mcfarhat! Keep up the good work!

Hi @igormuba!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @igormuba!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Loading...

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.030
BTC 66408.50
ETH 3486.20
USDT 1.00
SBD 2.70