Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Blockchain is a time-stamped decentralized series of fixed records that contains data of any size is controlled by a large network of computers that are scattered around the globe and not owned by a single organization. Every block is secured and connected with each other using hashing technology which protects it from being tampered by an unauthorized person.
Creating Blockchain using Python, mining new blocks, and displaying the whole blockchain:
- The data will be stored in JSON format which is very easy to implement and easy to read. The data is stored in a block and the block contains multiple data. Each and every minute multiple blocks are added and to differentiate one from the other we will use fingerprinting.
- The fingerprinting is done by using hash and to be particular we will use the SHA256 hashing algorithm. Every block will contain its own hash and also the hash of the previous function so that it cannot get tampered with.
- This fingerprinting will be used to chain the blocks together. Every block will be attached to the previous block having its hash and to the next block by giving its hash.
- The mining of the new block is done by giving successfully finding the answer to the proof of work. To make mining hard the proof of work must be hard enough to get exploited.
- After mining the block successfully the block will then be added to the chain.
- After mining several blocks the validity of the chain must be checked in order to prevent any kind of tampering with the blockchain.
- Then the web app will be made by using Flask and deployed locally or publicly as per the need of the user.
Python # Python program to create Blockchain# For timestampimport datetime# Calculating the hash# in order to add digital# fingerprints to the blocksimport hashlib# To store data# in our blockchainimport json# Flask is for creating the web# app and jsonify is for# displaying the blockchainfrom flask import Flask, jsonifyclass Blockchain: # This function is created # to create the very first # block and set its hash to "0" def __init__(self): self.chain = [] self.create_block(proof=1, previous_hash='0') # This function is created # to add further blocks # into the chain def create_block(self, proof, previous_hash): block = {'index': len(self.chain) + 1, 'timestamp': str(datetime.datetime.now()), 'proof': proof, 'previous_hash': previous_hash} self.chain.append(block) return block # This function is created # to display the previous block def print_previous_block(self): return self.chain[-1] # This is the function for proof of work # and used to successfully mine the block def proof_of_work(self, previous_proof): new_proof = 1 check_proof = False while check_proof is False: hash_operation = hashlib.sha256( str(new_proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:5] == '00000': check_proof = True else: new_proof += 1 return new_proof def hash(self, block): encoded_block = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(encoded_block).hexdigest() def chain_valid(self, chain): previous_block = chain[0] block_index = 1 while block_index < len(chain): block = chain[block_index] if block['previous_hash'] != self.hash(previous_block): return False previous_proof = previous_block['proof'] proof = block['proof'] hash_operation = hashlib.sha256( str(proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:5] != '00000': return False previous_block = block block_index += 1 return True# Creating the Web# App using flaskapp = Flask(__name__)# Create the object# of the class blockchainblockchain = Blockchain()# Mining a new block@app.route('/mine_block', methods=['GET'])def mine_block(): previous_block = blockchain.print_previous_block() previous_proof = previous_block['proof'] proof = blockchain.proof_of_work(previous_proof) previous_hash = blockchain.hash(previous_block) block = blockchain.create_block(proof, previous_hash) response = {'message': 'A block is MINED', 'index': block['index'], 'timestamp': block['timestamp'], 'proof': block['proof'], 'previous_hash': block['previous_hash']} return jsonify(response), 200# Display blockchain in json format@app.route('/get_chain', methods=['GET'])def display_chain(): response = {'chain': blockchain.chain, 'length': len(blockchain.chain)} return jsonify(response), 200# Check validity of blockchain@app.route('/valid', methods=['GET'])def valid(): valid = blockchain.chain_valid(blockchain.chain) if valid: response = {'message': 'The Blockchain is valid.'} else: response = {'message': 'The Blockchain is not valid.'} return jsonify(response), 200# Run the flask server locallyapp.run(host='127.0.0.1', port=5000)
Output (mine_block):
{
"index":2,
"message":"A block is MINED",
"previous_hash":"734dd03fe55286521079efedac571577cc9588aad79afe49c468e3d5153a79d1",
"proof":632238,
"timestamp":"2020-06-01 22:47:59.309000"
}Output (get_chain):
{
"chain":[{"index":1,
"previous_hash":"0",
"proof":1,
"timestamp":"2020-06-01 22:47:05.915000"},{"index":2,
"previous_hash":"734dd03fe55286521079efedac571577cc9588aad79afe49c468e3d5153a79d1",
"proof":632238,
"timestamp":"2020-06-01 22:47:59.309000"}],
"length":2
}Output(valid):
{"message":"The Blockchain is valid."}
Full Explanation:
- The code begins by importing the necessary libraries.
- The hashlib library is used to calculate a digital fingerprint for each block in the blockchain.
- This fingerprint is then stored in a variable called hash.
- Next, the data needed to create a blockchain web app is imported.
- This includes the Flask web application framework and the JSON library.
- Finally, the Blockchain class is created.
- The Blockchain class contains two main functions: Analyze and CreateBlockchainWebApp.
- The first function analyzes the code and creates an object model of it based on Python’s standard classes and modules.
- The second function creates a Flask web application based on this object model and stores all of the data needed to create a blockchain in it (including the digital fingerprints for each block).
- When you run this program, you will be prompted to enter some information about yourself (your name, email address, etc.).
- Once this information has been entered, you will be able to view your own personal blockchain!
- The code creates a Python program that will create a blockchain.
- The code first imports the necessary libraries for creating a blockchain.
- Next, it calculates the hash to add digital fingerprints to the blocks.
- Finally, it stores data in the blockchain using JSON.
- The code starts by creating an empty list called self.chain.
- The code then creates a function called create_block, which takes two arguments: proof and previous_hash.
- The create_block function first calculates the index of the block in the chain (that is, it adds 1 to the value of len(self.chain)).
- Then it sets the timestamp to datetime.datetime.now(), and stores the proof and previous_hash values for this block in block variables.
- Finally, self.chain is updated with this new block object.
- Next, the code creates a function called print_previous_block that prints out the contents of self.chain[-1], which is currently set to be equal to len(self.chain) + 1 – 1 because that’s how many blocks are in the chain at this point (the last block in the chain has index 0).
- Now let’s take a look at how these functions work together: When you call create_block(), you provide it with two arguments: proof and previous_hash (which are both Python objects).
- This tells create_block what data should be stored inside of its block variable (proof and previous_hash), as well
- The code first creates an empty list called self.chain.
- Next, it creates a function called create_block which takes in two arguments: proof and previous_hash.
- The purpose of this function is to create a new block on the blockchain and store its information within the block object.
- The next part of the code is responsible for displaying the previous block on the screen.
- This is done by using the print_previous_block function which takes in one argument: self.chain[-1].
- Finally, the last part of this code is responsible for performing proof of work.
- The code starts by creating an instance of the class Blockchain.
- This class stores information about the blockchain, including the previous block and proof.
- The code then uses the Proof of Work function to create a new block.
- The new block has a proof and hash that are based on the previous block and proof.
- Finally, the code prints out the current state of the blockchain and returns the URL for accessing it.
- The Proof of Work function is used to create new blocks in a blockchain network.
- It is a cryptographic algorithm that requires solving a difficult problem in order to generate a new block.
- The difficulty of this problem is adjusted so that it will take an average amount of time to generate a new block, regardless of how many people are mining on the network at any given time.
- The code creates a new block on the blockchain.
- This block contains the proof of work done by the current miner, as well as the previous block’s hash.
- The miner then prints this block to the console and stores it in a variable called previous_block.
- Next, they use Proof of Work to create a new hash for the new block.
- Finally, they store this hash in a variable called previous_proof and set the value of proof to be equal to this newly generated hash.
- The code starts by importing the necessary libraries.
- Next, it creates an instance of the Blockchain class.
- This class contains all the information about a blockchain, such as its length, index, and proof.
- Next, the code checks to see if the blockchain is valid.
- If it is valid, the code returns a response with a message that says The Blockchain is valid.
- Otherwise, the code returns a response with a message that says The Blockchain is not valid.
- Finally, the code displays the blockchain in json format onscreen using the display_chain() method.
- The code will display the blockchain in json format.
- It will also check the validity of the blockchain.
- If the blockchain is valid, it will return a message that states The Blockchain is valid.
- If the blockchain is not valid, it will return a message that states The Blockchain is not valid
Please Login to comment...
Similar Reads
Full vs Simple Payment Verification in Blockchain
This article focuses on discussing various ways of payment verification. let's first start with the introduction of the basic terminologies that will be used in this article. 1. Authentication: Authentication refers to systems that authenticate users' access to resources on the Bitcoin and other digital currency's underlying technology. 2. Authoriz
5 min read
Create a Simple Two Player Game using Turtle in Python
Prerequisites: Turtle Programming in Python TurtleMove game is basically a luck-based game. In this game two-players (Red & Blue), using their own turtle (object) play the game. How to play The game is played in the predefined grid having some boundaries. Both players move the turtle for a unit distance.Now both players flip the coin:if HEAD, t
4 min read
Create a Simple Sentiment Analysis WebApp using Streamlit
In this article, we will see how we can create a simple Sentiment Analysis webApp using with the help of Streamlit Module in Python. Required Modules: For this, we will need Three Modules. StreamlitTextBlobStreamlit_extras (optional). The module Streamlit_extras is optional because it will be used to add some extra features which will not affect th
4 min read
Python | Create simple animation for console-based application
As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility. We will try to replicate the loading animation as shown below: We will be using following modules - sys mo
2 min read
How to create a simple drawing board in Processing with Python Mode?
Processing is a programming language, and a development environment. It is an open-source software to create visual arts, graphics and animation using programming. It supports around 8 different modes, and in this article, we will be using Python Mode. In this article, we are going to create a simple drawing board using Processing with Python Mode.
3 min read
How to Create a Simple Messagebox in Python
Python has the capability to create GUI applications using libraries like tkinter and PyQt5. These libraries provide easy-to-use methods for creating various GUI elements, including messageboxes. In this article, we will explore both this approaches to create a simple messagebox in Python. Create A Simple Messagebox In PythonBelow are the possible
2 min read
Decentralized Voting System using Blockchain
Blockchain is a technology that is rapidly gaining momentum in era of industry 4.0. With high security and transparency provisions, it is being widely used in supply chain management systems, healthcare, payments, business, IoT, voting systems, etc. Why do we need it? Current voting systems like ballot box voting or electronic voting suffer from va
4 min read
Build a Authentication Using Blockchain
Normally authentication is seen using databases like MYSQL, Firebase, MongoDB, etc. One of the biggest drawbacks is the chance of the data getting corrupted. The data can be modified by anyone who is in control of the database itself.To overcome the above problem here a web app authentication using blockchain will be created. Components in Web Auth
9 min read
How to deploy Smart Contracts using Ethers.js and Node.js on Goerli Testnet Blockchain from Back-end ?
In this article, we will be deploying smart contracts on blockchain from back-end, so that we do not have to require hardhat or truffle frameworks and their commands to deploy a smart contract or if somebody doesn't want to use these frameworks. Since we have to run manual commands of these frameworks in the terminal to deploy Smart Contracts. We c
9 min read
Blockchain - Creating Elliptic Curve Keys using OpenSSL
Elliptic curve cryptography is employed to implement public key cryptography. It had been discovered by Victor Miller of IBM and Neal Koblitz of the University of Washington in 1985. ECC, popularly utilized, is an acronym for Elliptic Curve Cryptography. It's grounded on recent mathematics and delivers a reasonably more secure foundation than the f
3 min read
Blockchain - Encrypt & Decrypt Files With Password Using OpenSSL
Encryption is the process of encoding information or data in such a way that only authorized parties can access it. The process of encrypting information involves using a mathematical algorithm to transform the original information, known as plaintext, into a form that is unreadable to anyone who does not have the means to decrypt it, known as ciph
5 min read
Implementing the Proof-of-Work Algorithm in Python for Blockchain Mining
Blockchain technology is a decentralized and immutable ledger of digital transactions that has the potential to revolutionize many industries. Mining is one of the key components of blockchain, which is the process of validating transactions and creating new blocks on the blockchain. The Proof-of-Work (PoW) algorithm is used to ensure that miners a
10 min read
How to create a simple CGI script?
In this article, we will explore how to create a simple CGI (Common Gateway Interface) script on a Windows machine but before that, we need some basic ideas about these technologies ( CGI Script, HTTP, Web Server ).CGI Script: A CGI script is a program that runs on a web server and generates dynamic web content. It's often used for processing web f
2 min read
Simple registration form using Python Tkinter
Prerequisites: Tkinter Introduction, openpyxl module.Python provides the Tkinter toolkit to develop GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit. Let's make a simple information form GUI application using Tkinter. In this application, User has to fill up the required info
5 min read
Python | Simple GUI calculator using Tkinter
Prerequisite: Tkinter Introduction, lambda function Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI a
6 min read
Python | Simple FLAMES game using Tkinter
Prerequisites: Introduction to TkinterProgram to implement simple FLAMES game Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and e
5 min read
Python | Simple calculator using Tkinter
Prerequisite : Tkinter IntroductionPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Cr
3 min read
Python | Make a simple window using kivy
Kivy is a platform independent as it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it Does not mean that it can not be used on Desktops applications. Use this command To install kivy: pi
5 min read
Python | Thresholding techniques using OpenCV | Set-1 (Simple Thresholding)
Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255). Thresholding is a very popular
3 min read
Python - Convert simple lines to bulleted lines using the Pyperclip module
Pyperclip is the cross-platform Python module which is used for copying and pasting the text to the clipboard. Let's suppose you want to automate the task of copying the text and then convert them to the bulleted points. This can be done using the pyperclip module. Consider the below examples for better understanding. Examples: Clipboard Content :
2 min read
Build a simple Quantum Circuit using IBM Qiskit in Python
Qiskit is an open source framework for quantum computing. It provides tools for creating and manipulating quantum programs and running them on prototype quantum devices on IBM Q Experience or on simulators on a local computer. Let's see how we can create simple Quantum circuit and test it on a real Quantum computer or simulate in our computer local
5 min read
Simple Port Scanner using Sockets in Python
Prerequisites: Socket Programming in Python Before going to the programming, let us discuss about ports. In this article, we will check the virtual ports of a server or websites, or localhost. Every port has a unique number. There are 65,535 ports available in a host starting from 0. We can assign the ports for any services. Example 1: In this prog
3 min read
Setting up a simple HTTP server using Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation On the terminal run the following stateme
2 min read
Building a Simple Application using KivyMD in Python
KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we will see how to make a simple application in KivyMD using Screen, Label, TextFieldInput, and Bu
3 min read
Simple Chat Room using Python
This article demonstrates - How to set up a simple Chat Room server and allow multiple clients to connect to it using a client-side script. The code uses the concept of sockets and threading. Socket programming Sockets can be thought of as endpoints in a communication channel that is bi-directional and establishes communication between a server and
8 min read
Simple BMI calculator using Python
In this article, we will guide you through the process of building a straightforward Body Mass Index (BMI) calculator using Python. To enhance user interaction, we will implement a simple graphical user interface (GUI) form. This form will allow users to input their weight and height, and with the help of the Django Framework, the BMI will be autom
4 min read
Generate simple ASCII tables using prettytable in Python
Prettytable is a Python library used to print ASCII tables in an attractive form and to read data from CSV, HTML, or database cursor and output data in ASCII or HTML. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border. InstallationIn order to be able to use prettytable libra
5 min read
Simple Chatbot application using Python, GoogleAPIKey
Google-GenerativeAI is Google AI Python SDK. It uses Gemini to build AI-powered features. In this article, we will see how to create a Simple Chatbot application using Python GoogleAPIKey. What is Google-GenerativeAI?Google-GenerativeAI is nothing but Google AI Python SDK. It enables to use of Gemini to build AI-powered features and applications. T
4 min read
Flutter and Blockchain - Hello World Dapp
This tutorial will take you through the process of building your first mobile dapp - Hello World Dapp! This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of the Flutter framework but are new to mobile dapps. In this tutorial we will be covering: Setting up the development environmentCrea
9 min read
Integration of Artificial Intelligence and BlockChain
Artificial Intelligence and Blockchain are proving to be quite a powerful combination, improving virtually every industry in which they're implemented. These technologies can be combined to upgrade everything from food supply chain logistics and healthcare record sharing to media royalties and financial security. The integration of AI and Blockchai
8 min read
Article Tags :
Practice Tags :
Trending in News
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });