HTML form send data to google sheet with time stamp - javascript

i have success send data to my google sheet from HTML
function submit_form() {
var complete = true;
var error_color = '#FFD9D9';
var fields = ['name','phonenum','monthlysalary','totalamount','types'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
row += '"'+value+'",';
}
}
if(complete) {
row = row.slice(0, -1);
var gs_sid = 'xxx';
var gs_clid = 'xxx';
var gs_clis = 'xxx';
var gs_rtok = 'xxx';
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Google!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.send(gs_body);
}
};
xhr.send();
}
}
Now i having a problem, i would like to make the google sheets will auto adding timestamp when i send the data into google form. Its anyway to do it?
Thank you

Related

Browser getting stuck to upload large files

I am using basic javascript and trying to upload a file appx 500Mb, but my browser is getting stuck. Below is my javascript code
main.js
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
var multipleUploadForm = document.querySelector('#multipleUploadForm');
var multipleFileUploadInput = document.querySelector('#multipleFileUploadInput');
var multipleFileUploadError = document.querySelector('#multipleFileUploadError');
var multipleFileUploadSuccess = document.querySelector('#multipleFileUploadSuccess');
var asyncMltipleUploadForm = document.querySelector('#asyncMltipleUploadForm');
var asyncMultipleFileUploadInput = document.querySelector('#asyncMltipleUploadInput');
var asyncMultipleFileUploadError = document.querySelector('#asyncMultipleFileUploadError');
var asyncMultipleFileUploadSuccess = document.querySelector('#asyncMultipleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
// singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
function resolveAfter2Seconds(file) {
return new Promise(resolve => {
// setTimeout(() => {
resolve(uploadSingleFile(file));
// }, null);
} );
}
async function asynchUploadMultipleFiles(files) {
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
// formData.append("files", files[index]);
var startDate = new Date();
await resolveAfter2Seconds(files[index]);
var endDate = new Date();
var diff = endDate - startDate;
asyncMultipleFileUploadSuccess.innerHTML = "time taken :::: " + diff;
asyncMultipleFileUploadSuccess.style.display = "block";
}
}
function uploadMultipleFiles(files) {
var startDate = new Date();
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
formData.append("files", files[index]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadMultipleFiles");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
multipleFileUploadError.style.display = "none";
var content = "<p>All Files Uploaded Successfully</p>";
// for(var i = 0; i < response.length; i++) {
// content += "<p>DownloadUrl : <a href='" + response[i].fileDownloadUri + "' target='_blank'>" + response[i].fileDownloadUri + "</a></p>";
// }
var endDate = new Date();
var diff = endDate - startDate;
multipleFileUploadSuccess.innerHTML = content + "time taken :::: " + diff;
multipleFileUploadSuccess.style.display = "block";
} else {
multipleFileUploadSuccess.style.display = "none";
multipleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
// console.log(xhr.responseText);
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
multipleUploadForm.addEventListener('submit', function(event){
var files = multipleFileUploadInput.files;
if(files.length === 0) {
multipleFileUploadError.innerHTML = "Please select at least one file";
multipleFileUploadError.style.display = "block";
}
uploadMultipleFiles(files);
event.preventDefault();
}, true);
asyncMltipleUploadForm.addEventListener('submit', function(event){
var files = asyncMultipleFileUploadInput.files;
if(files.length === 0) {
asyncMultipleFileUploadError.innerHTML = "Please select at least one file";
asyncMultipleFileUploadError.style.display = "block";
}
asynchUploadMultipleFiles(files);
event.preventDefault();
}, true);
Can you please help

A piece of javascript in footer.php wordpress does work on PC but not on mobile

I have the following code in my footer.php on my wordpress website
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function() {
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/xxxxx/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = response.result;
for (var i in result) {
var e = result[i];
if (e) {
var li = document.createElement('li');
if (e.url) {
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.name;
li.appendChild(a);
} else {
li.textContent = e.name;
}
resultList.appendChild(li);
}
}
busyDiv.hidden = true;
resultDiv.hidden = false;
}
}
var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','xxx','yyyy'];
var params = [];
for (var i in fields) {
var field = fields[i];
params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));
questionDiv.hidden=true;
busyDiv.hidden=false;
return false;
};
}
</script>
This has allowed me to write and quote data from a google sheet
Now all this works on PC but it delivers 404 not found error on mobile site and the website itself is preset to be mobile responsive.
Can somebody help please?
Jane
What does your form html look like? I suspect that your mobile browser is trying to submit the form via the standard - non AJAX way and therefore is directing the browser to the url in the "action" attribute of your form. Try the following to stop this default behaviour
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function(evt) {
evt.preventDefault();

How populate database records into my table ajax

So i go this information and have a empty table name categorytable so i have to have records stored in categoryList for the below code to work. so what do i write in categoryList which is to fetch the record from my category manager and display the data from sql
</table>
<script>
$(document).ready(function () {
var categoryList = [];
var $courseTableElement = $('#categoryTable');
var $rowElement;
var $cellElement;
var index = 0;
for (index = 0; index < categoryList.length; index++) {
$rowElement = $('<tr></tr>');
$cellElement = $('<td></td>', { text: categoryList[index].CategoryName });
$rowElement.append($cellElement);
$cellElement = $('<td></td>', { text: categoryList[index].CategoryId });
$rowElement.append($cellElement);
$courseTableElement.append($rowElement);
}
});
</script>
public List<Category> getAllCategory(string inUserId)
{
DataSet ds = new DataSet();
List<Category> categoryList = new List<Category>();
string sqlText = "";
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn; //setup the
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
sqlText = "SELECT CategoryId,CategoryName,CreatedBy,CreatedAt,UpdatedBy,UpdatedAt " +
" FROM Category ";
cmd.CommandText = sqlText;
cmd.Parameters.Add("#inCurrentUserId", SqlDbType.VarChar, 200).Value = inUserId;
da.Fill(ds, "CategoryData");
cmd.CommandText = sqlText;
}//using SqlDataAdapter da
cn.Close();
}//using SQLCommand cmd
}//using SQLConnection cn
foreach (DataRow dr in ds.Tables["CategoryData"].Rows)
{
Category category = new Category();
category.CategoryId = Int32.Parse(dr["CategoryId"].ToString());
category.CategoryName = dr["CategoryName"].ToString();
category.CreatedBy = dr["CreatedBy"].ToString();
category.CreatedAt = DateTime.Parse(dr["CreatedAt"].ToString());
category.UpdatedBy = dr["UpdatedBy"].ToString();
category.UpdatedAt = DateTime.Parse(dr["UpdatedAt"].ToString());
categoryList.Add(category);
}
return categoryList;
}
You just need to make an ajax request to your server and grab that data. I'm making a couple of assumptions.
That getAllCategory is accessible to the frontend via webapi or something of the sort.
That getAllCategory will return proper json.
function getDataFromServer(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("get",url);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readystate === 4 && xmlhttp.status === 200){
//data was retrieved successfully.
callback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.send();
}
$(document).ready(function () {
//the path to action must include the id in querystring
var url = 'path_to_action'
getDataFromServer(url, function(data){
var courseTableElement = $('#categoryTable');
for(var i = 0; i < data.length; i++){
var row = $('<tr></tr>');
var cell1 = $('<td></td>, { text: data[i].CategoryName } );
var cell2 = $('<td></td>, { text: data[i].CategoryId } );
row.append(cell1);
row.append(cell2);
courseTableElement.append(row);
}
}
});

JavaScript error with splitting string into array

I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!
You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}
Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}

Downloading binary data using XMLHttpRequest, without overrideMimeType

I am trying to retrieve the data of an image in Javascript using XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.celticfc.net/images/doc/celticcrest.png");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var resp = xhr.responseText;
console.log(resp.charCodeAt(0) & 0xff);
}
};
xhr.send();
The first byte of this data should be 0x89, however any high-value bytes return as 0xfffd (0xfffd & 0xff being 0xfd).
Questions such as this one offer solutions using the overrideMimeType() function, however this is not supported on the platform I am using (Qt/QML).
How can I download the data correctly?
Google I/O 2011: HTML5 Showcase for Web Developers: The Wow and the How
Fetch binary file: new hotness
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
uInt8Array[i] = this.response[i];
}
var byte3 = uInt8Array[4]; // byte at offset 4
}
}
xhr.send();
I'm not familiarized with Qt but i found this in their documentation
string Qt::btoa ( data )
Binary to ASCII - this function returns a base64 encoding of data.
So, if your image is a png you can try:
resp = "data:image/png;base64," + btoa(resp);
document.write("<img src=\""+resp+"\">");
Qt version 5.13.1(support native Promise in qml env), prue qml.
function fetch, like node-fetch
function hexdump, dump the data as hex, just use the linux command hexdump to check.
function createResponse(xhr) {
let res = {};
function headersParser() {
let headersRaw = {};
let lowerCaseHeaders = {};
let rawHeaderArray = xhr.getAllResponseHeaders().split("\n");
for(let i in rawHeaderArray) {
let rawHeader = rawHeaderArray[i];
let headerItem = rawHeader.split(":");
let name = headerItem[0].trim();
let value = headerItem[1].trim();
let lowerName = name.toLowerCase();
headersRaw[name] = value;
lowerCaseHeaders [lowerName] = value;
}
return {
"headersRaw": headersRaw,
"lowerCaseHeaders": lowerCaseHeaders
};
}
res.headers = {
__alreayParse : false,
raw: function() {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__headersRaw;
},
get: function(headerName) {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__lowerCaseHeaders[headerName.toLowerCase()];
}
};
res.json = function() {
if(res.__json) {
return res.__json;
}
return res.__json = JSON.parse(xhr.responseText);
}
res.text = function() {
if (res.__text) {
return res.__text;
}
return res.__text = xhr.responseText;
}
res.arrayBuffer = function() {
if (res.__arrayBuffer) {
return res.__arrayBuffer;
}
return res.__arrayBuffer = new Uint8Array(xhr.response);
}
res.ok = (xhr.status >= 200 && xhr.status < 300);
res.status = xhr.status;
res.statusText = xhr.statusText;
return res;
}
function fetch(url, options) {
return new Promise(function(resolve, reject) {
let requestUrl = "";
let method = "";
let headers = {};
let body;
let timeout;
if (typeof url === 'string') {
requestUrl = url;
method = "GET";
if (options) {
requestUrl = options['url'];
method = options['method'];
headers = options['headers'];
body = options['body'];
timeout = options['timeout'];
}
} else {
let optionsObj = url;
requestUrl = optionsObj['url'];
method = optionsObj['method'];
headers = optionsObj['headers'];
body = optionsObj['body'];
timeout = optionsObj['timeout'];
}
let xhr = new XMLHttpRequest;
if (timeout) {
xhr.timeout = timeout;
}
// must set responseType to arraybuffer, then the xhr.response type will be ArrayBuffer
// but responseType not effect the responseText
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
// readyState as follow: UNSENT, OPENED, HEADERS_RECEIVED, LOADING, DONE
if(xhr.readyState === XMLHttpRequest.DONE) {
resolve(createResponse(xhr));
}
};
xhr.open(method, requestUrl);
// todo check headers
for(var iter in headers) {
xhr.setRequestHeader(iter, headers[iter]);
}
if("GET" === method || "HEAD" === method) {
xhr.send();
} else {
xhr.send(body);
}
});
}
function hexdump(uint8array) {
let count = 0;
let line = "";
let lineCount = 0;
let content = "";
for(let i=0; i<uint8array.byteLength; i++) {
let c = uint8array[i];
let hex = c.toString(16).padStart (2, "0");
line += hex + " ";
count++;
if (count === 16) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
count = 0;
lineCount++;
}
}
if(line) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
// count = 0;
lineCount++;
}
content+= (lineCount).toString (16).padStart (7, "0") + count.toString(16) +"\n";
return content;
}
fetch("https://avatars2.githubusercontent.com/u/6630355")
.then((res)=>{
try {
let headers = res.headers.raw();
console.info(`headers:`, JSON.stringify(headers));
let uint8array = res.arrayBuffer();
let hex = hexdump(uint8array);
console.info(hex)
}catch(error) {
console.trace(error);
}
})
.catch((error)=>{
});

Categories

Resources