This is a simple web application which is done using simple HTML elements, Jquery, and data transaction with Google spread sheet is done using Google App Script.
This app consists of 2 Parts
- App Script
- HTML with JQuery.
[maxbutton id=”3″ ] [maxbutton id=”4″ ]
1. App Script
Step 1 : Create new app script project. Click here to create App Script.
Step 2 : Copy and paste the below script which handles two attributes (id,name). You can change the logic, attributes as required.
function doGet(e){
var op = e.parameter.action;
var ss=SpreadsheetApp.openByUrl("Your Spread sheet URL");
var sheet = ss.getSheetByName("Sheet1");
if(op=="insert")
return insert_value(e,sheet);
//Make sure you are sending proper parameters
if(op=="read")
return read_value(e,ss);
if(op=="update")
return update_value(e,sheet);
if(op=="delete")
return delete_value(e,sheet);
}
//Recieve parameter and pass it to function to handle
function insert_value(request,sheet){
var id = request.parameter.id;
var country = request.parameter.name;
var flag=1;
var lr= sheet.getLastRow();
for(var i=1;i<=lr;i++){
var id1 = sheet.getRange(i, 2).getValue();
if(id1==id){
flag=0;
var result="Id already exist..";
} }
//add new row with recieved parameter from client
if(flag==1){
var d = new Date();
var currentTime = d.toLocaleString();
var rowData = sheet.appendRow([currentTime,id,country]);
var result="Insertion successful";
}
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function read_value(request,ss){
var output = ContentService.createTextOutput(),
data = {};
//Note : here sheet is sheet name , don't get confuse with other operation
var sheet="sheet1";
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) { return p.replace(/\s+/g, '_'); });
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
}
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
//update function
function update_value(request,sheet){
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var flag=0;
var country = request.parameter.name;
var lr= sheet.getLastRow();
for(var i=1;i<=lr;i++){
var rid = sheet.getRange(i, 2).getValue();
if(rid==id){
sheet.getRange(i,3).setValue(country);
var result="value updated successfully";
flag=1;
}
}
if(flag==0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function delete_value(request,sheet){
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var country = request.parameter.name;
var flag=0;
var lr= sheet.getLastRow();
for(var i=1;i<=lr;i++){
var rid = sheet.getRange(i, 2).getValue();
if(rid==id){
sheet.deleteRow(i);
var result="value deleted successfully";
flag=1;
}
}
if(flag==0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Step 3 : Change the url of the spread sheet. Make sure sheet is shared .[anyone with the link can view]
Step 4 : Go to Publish -> Deploy as web app. A window pop up, here ->Who has access to the app: -> Anyone
then Publish/Update. Copy the published url and store it.
2. HTML PART
Step 1 : Create a file crud_test.html and copy the below code.
<html>
<head>
<style>
table, th, td
{
margin:10px 0;
border:solid 1px #333;
padding:2px 4px;
font:15px Verdana;
}
th {
font-weight:bold;
}
#loader {
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid blue;
border-bottom: 16px solid blue;
width: 60px;
height: 60px;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
visibility:hidden;
}
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
var script_url = "Your published web app url";
// Make an AJAX call to Google Script
function insert_value() {
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
$('#mySpinner').addClass('spinner');
var id1= $("#id").val();
var name= $("#name").val();
var url = script_url+"?callback=ctrlq&name="+name+"&id="+id1+"&action=insert";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
function update_value(){
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
var id1= $("#id").val();
var name= $("#name").val();
var url = script_url+"?callback=ctrlq&name="+name+"&id="+id1+"&action=update";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
function delete_value(){
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
$('#mySpinner').addClass('spinner');
var id1= $("#id").val();
var name= $("#name").val();
var url = script_url+"?callback=ctrlq&name="+name+"&id="+id1+"&action=delete";
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: "GET",
dataType: "jsonp"
});
}
// print the returned data
function ctrlq(e) {
$("#re").html(e.result);
$("#re").css("visibility","visible");
read_value();
}
function read_value() {
$("#re").css("visibility","hidden");
document.getElementById("loader").style.visibility = "visible";
var url = script_url+"?action=read";
$.getJSON(url, function (json) {
// Set the variables from the results array
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
var header = table.createTHead();
var row = header.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<b>ID</b>";
cell2.innerHTML = "<b>Name</b>";
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < json.records.length; i++) {
tr = table.insertRow(-1);
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = json.records[i].ID;
tabCell = tr.insertCell(-1);
tabCell.innerHTML = json.records[i].NAME;
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
document.getElementById("loader").style.visibility = "hidden";
$("#re").css("visibility","visible");
});
}
</script>
</head>
<body>
<div align="center">
<h1>CRUD OPERATION ON GOOGLE SPREAD SHEET, WEB APPLICATION USING GOOGLE APP SCRIPT .</h1>
<p>This is simple application, You can develop your own logic based on your requiremnets.<p>
<p>Be careful with the parameters you are sending, it should match the parameters that are recived in google app script.</p>
<form >
ID
<input type = "text" name ="id" id="id">
Name
<input type = "text" name ="name" id="name">
</form>
<div id="loader"></div>
<p id="re"></p>
<input type = "button" id = "b1" onClick="insert_value()" value = "Insert"></input>
<input type="button" onclick="read_value()" value="Read" />
<input type="button" onclick="update_value()" value="Update" />
<input type="button" onclick="delete_value()" value="Delete" />
<a href="https://docs.google.com/spreadsheets/d/1OmqvphAqP4WEcrsZAMNNeL2YVn3RJffVOIGgdPiyEVA/edit?usp=sharing" target="_blank">Click here to open Spread Sheet </a>
<div id="showData"></div>
</div>
</body>
<div align="center">
<p>ANDROID LABS 2017 | All Rights Reserved</p>
</div>
<html>
Step 2 : Change the script url to your published web app script which was stored in step 4
<script> var script_url = "https://script.google.com/macros/s/AKfycbwyW-xxxxxxxxxxxxxxxxxxx-P1lzLGt/exec?"; ----------------------------- ----------------------------- </script>
Step 3 : Now check for operations .
[maxbutton id=”3″ ] [maxbutton id=”4″ ]
Super JS API integration with Docs Sheet!!! Let’s share like more new learning. Thanks.
Thanks Karthik, I will be updating with new experiments..
your use table to show data, how to loop this?
innerHTML = json.records[i].ID;
innerHTML = json.records[i].name;
into this:
id 1 name 1
id 2 name 2
id 3 name 3
id 4 name 4
please save my day thanks….
Data is stored in records array, so use it wherever necessary. You can create above mentioned scenario dynamically also.. if you need further assistance mail to admin@androidlabs.info
ok, wait i will send email bro….
You can refer this https://stackoverflow.com/questions/5308125/how-to-create-list-in-html-dynamically
hello, thanks for your example
i wish to expand the colums ,can please help me
please email me to my registered email
did u figure out how to add more column im trying can u help me
How to Filter data using column like read_value()
Please share filter column code
Hello Shubham , can you elaborate
Sorry for late reply ,
Searching records by ID or Name for EX:- Search Name Like “John” filter Column_Name John record fetch
ID Name
1 John
4 John
6 John
8 John
Please provide code if possible,
Thanks for reply.
https://uploads.disquscdn.com/images/cf6fc46cee9ed7ed670e827b1172257e0147c1981492ee001a63bdf24d7b1d5d.png
Hi Shubham, You can use client side filter by writing functions or using some ready js..available.. For reference follow below sites..
1)https://www.w3schools.com/howto/howto_js_filter_table.asp
2)https://www.w3schools.com/howto/howto_js_filter_lists.asp
3)https://www.w3schools.com/w3js/w3js_filters.asp
Hope this will help you
Hi Sir,
My previous post misunderstanding,
i have get filter data server side not client side
Recent Posts:- “Google Sheet As DATABASE for your Android Application Part – 3 | [CRUD] Create, Read, Update, Delete operation on Google Sheets from Android App”
How to call using Javascript
i use this code throw some error:-
/*————Javascript Script———-*/
function read_value(){
$(“#re”).css(“visibility”,”hidden”);
document.getElementById(“loader”).style.visibility = “visible”;
$(‘#mySpinner’).addClass(‘spinner’);
var id1= $(“#id”).val();
var url = script_url+”?callback=ctrlq&id=”+id1+”&action=read”;
var request = jQuery.ajax({
crossDomain: true,
url: url ,
method: “GET”,
dataType: “jsonp”
});
}
/*————App Script———-*/
if (op == “read”)
return read_value(e, sheet);
function read_value(request, sheet) {
var id = request.parameter.id;
var name;
var record = {};
//var place = request.parameter.place;
var flag = 1;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var id1 = sheet.getRange(i, 2).getValue();
if (id1 == id) {
flag = 0;
name = sheet.getRange(i, 3).getValue();
var result = JSON.stringify({
"user": {
"id": id,
"name": name
}
});
}
}
return ContentService
.createTextOutput(result)
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function doGet(e) {
var op = e.parameter.action;
var ss = SpreadsheetApp.openByUrl(“……”);
var sheet = ss.getSheetByName(“Sheet1”);
if (op == “insert”)
return insert_value(e, sheet);
//Make sure you are sending proper parameters
if (op == “read”)
return read_value(e, sheet);
if (op == “update”)
return update_value(e, sheet);
if (op == “delete”)
return delete_value(e, sheet);
if (op == “readall”)
return read_all_value(e, ss);
}
//Recieve parameter and pass it to function to handle
function insert_value(request, sheet) {
var id = request.parameter.id;
var country = request.parameter.name;
var flag = 1;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var id1 = sheet.getRange(i, 2).getValue();
if (id1 == id) {
flag = 0;
var result = "Id already exist..";
}
}
//add new row with recieved parameter from client
if (flag == 1) {
var d = new Date();
var currentTime = d.toLocaleString();
var rowData = sheet.appendRow([currentTime, id, country]);
var result = "Insertion successful";
}
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(result) .setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function read_all_value(request, ss) {
var output = ContentService.createTextOutput(),
data = {};
//Note : here sheet is sheet name , don't get confuse with other operation var sheet="sheet1";
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) {
return p.replace(/s+/g, '_');
});
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() – 1, sh.getLastColumn()).getValues(); }
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
//update function
function update_value(request, sheet) {
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var flag = 0;
var country = request.parameter.name;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var rid = sheet.getRange(i, 2).getValue();
if (rid == id) {
sheet.getRange(i, 3).setValue(country);
var result = "value updated successfully";
flag = 1;
}
}
if (flag == 0)
var result = "id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(result) .setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function delete_value(request, sheet) {
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var country = request.parameter.name;
var flag = 0;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var rid = sheet.getRange(i, 2).getValue();
if (rid == id) {
sheet.deleteRow(i);
var result = "value deleted successfully";
flag = 1;
}
}
if (flag == 0)
var result = "id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(result) .setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function read_value(request, sheet) {
var id = request.parameter.id;
var name;
var record = {};
//var place = request.parameter.place;
var flag = 1;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var id1 = sheet.getRange(i, 2).getValue();
if (id1 == id) {
flag = 0;
name = sheet.getRange(i, 3).getValue();
var result = JSON.stringify({
"user": {
"id": id,
"name": name
}
});
}
}
return ContentService
.createTextOutput(result) .setMimeType(ContentService.MimeType.JAVASCRIPT);
}
HI,
How to store a picture and retrieve or view the existing picture using google drive
Moreover, how to retrieve the data one by one by clicking on the next button or searching the record based on the unique code?
Please provide your sample coding if possible.
Regards, Mani
Sorry for late reply ,, I am working on uploading images, I will update it soon..
As of now you can refer http://www.androidlabs.info/youtube/google-sheet-as-database-for-your-android-application-part-4-add-images-optimized/
Sorry for late reply ,
Searching records by ID or Name for EX:- Search Name Like “John” filter Column_Name John record fetch
ID Name
1 John
4 John
6 John
Please provide code if possible,
Thanks for reply.
Hello! thank you for your post. How to get value of other input types like checkbox and radio buttons?
very good, but i have a question. could please? i need only on cel, type A1 or b2.
thank !
Good example, but i have one question after rename Sheet1 with another name in spreadsheet, data not inserted into spreadsheet
Go through the script … And change the name in the script also
var sheet = ss.getSheetByName(“lavanya”);
replace the Sheet1 with
lavanya (var sheet = ss.getSheetByName(“lavanya”); )
var sheet=”lavanya”;
==================Below is my script File===================
function doGet(e){
var op = e.parameter.action;
var ss=SpreadsheetApp.openByUrl(“https://docs.google.com/spreadsheets/d/1NkT3NYdLobGk1qx23hkcLWIaXi6yfczJ58CTBy3c3vg/edit#gid=0”);
var sheet = ss.getSheetByName(“lavanya”);
if(op==”insert”)
return insert_value(e,sheet);
//Make sure you are sending proper parameters
if(op==”read”)
return read_value(e,ss);
if(op==”update”)
return update_value(e,sheet);
if(op==”delete”)
return delete_value(e,sheet);
}
//Recieve parameter and pass it to function to handle
function insert_value(request,sheet){
var id = request.parameter.id;
var country = request.parameter.name;
var flag=1;
var lr= sheet.getLastRow();
for(var i=1;i<=lr;i++){
var id1 = sheet.getRange(i, 2).getValue();
if(id1==id){
flag=0;
var result="Id already exist..";
} }
//add new row with recieved parameter from client
if(flag==1){
var d = new Date();
var currentTime = d.toLocaleString();
var rowData = sheet.appendRow([currentTime,id,country]);
var result="Insertion successful";
}
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function read_value(request,ss){
var output = ContentService.createTextOutput(),
data = {};
//Note : here sheet is sheet name , don't get confuse with other operation
var sheet="lavanya";
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) { return p.replace(/s+/g, '_'); });
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() – 1, sh.getLastColumn()).getValues();
}
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
//update function
function update_value(request,sheet){
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var flag=0;
var country = request.parameter.name;
var lr= sheet.getLastRow();
for(var i=1;i<=lr;i++){
var rid = sheet.getRange(i, 2).getValue();
if(rid==id){
sheet.getRange(i,3).setValue(country);
var result="value updated successfully";
flag=1;
}
}
if(flag==0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
function delete_value(request,sheet){
var output = ContentService.createTextOutput();
var id = request.parameter.id;
var country = request.parameter.name;
var flag=0;
var lr= sheet.getLastRow();
for(var i=1;i<=lr;i++){
var rid = sheet.getRange(i, 2).getValue();
if(rid==id){
sheet.deleteRow(i);
var result="value deleted successfully";
flag=1;
}
}
if(flag==0)
var result="id not found";
result = JSON.stringify({
"result": result
});
return ContentService
.createTextOutput(request.parameter.callback + "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Please update on this..
Thanks! the example helped me a lot!!
this is great. I’m getting one “undefined” error in column 2 on read command Name. Also how would I add more columns for data?
Hello,
Can you please check url code. I’m getting same error as mentioned below before and after copying url.
var ss=SpreadsheetApp.openByUrl(“https://drive.google.com/open?id=1UDsrV2Czt4mgj_R-PvRL5h2VqmTi6TJE“);
Hi, Reading all the data when READ button action, can we read ID input data only and result output of ID input
Please help
Ref on this : CRUD operation on Google Spread Sheet using Google App script, HTML ,Jquery
Please guide me how would I add more columns to spreadsheet? Like Name,City, Phone etc. thank you for share this
Hello,
Have you got any feed-back on this? I am also interested in more data in my form inclusive check boxes etc.
Espen
Hi crazy code
Pls I need ur email address. Very urgent I need to send some hitch I have on this blog post.
Thank you.
Hello! thank you for your post. How to get value of other input types like checkbox and radio buttons?
Could you please provide example and also the creating dynamic on ur post, can it be done with DataTable() method
Thank you
how can i connect the login page with google spreadsheet? please help
https://uploads.disquscdn.com/images/8bb60601ba9bdb5bcd9a3d3e89af09d0890705904f54b65fcc1431d5572df909.png Hello i’m getting the parameter issue
How to add a column to a city?
how would I add more columns to spreadsheet?
READ button seems to just result in a spinning blue circle. Other functions work fine. Any advice?
Hi, how do i get the value for drop down list? It appears as undefined in the google sheets.
not working for me…