Function arguments are `[object Object]`

158 views
Skip to first unread message

Gilles

unread,
Feb 5, 2024, 2:35:25 AM2/5/24
to Google Apps Script Community
Hi,

I am using a script in a spreadsheet that has been running fine for months. Now suddenly the arguments passed to the JS function appear as `[object Object]` for no apparent reason.

Nothing has changed in the script, nothing has changed on the spreadsheet.

What gives?

Thanks for any advice.

Andrew Apell

unread,
Feb 7, 2024, 9:55:05 AM2/7/24
to Google Apps Script Community
I encountered this error about 3 years ago under very similar circumstances, but I cannot recall its exact solution.
If I'm to "guess", I think you are converting a variable to string and yet it should not be a string.

Try checking on Stack Overflow; I recall that I found the answer with them.

Keith Andersen

unread,
Feb 7, 2024, 7:26:55 PM2/7/24
to google-apps-sc...@googlegroups.com
Can you share the script?

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/e053d871-588c-4d7d-aa7e-711cba6998f7n%40googlegroups.com.

Gilles

unread,
Feb 7, 2024, 11:58:01 PM2/7/24
to Google Apps Script Community
Sure, it's not even mine, and as I said, it has worked for years before it broke the other day.
Here it is:

/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : ...)

This file is part of Contact Form to Database.

Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Contact Form to Database.
*/

/* This is a script to be used with a Google Spreadsheet to make it dynamically load data (similar to Excel IQuery)
Instructions:
1. Create a new Google Spreadsheet
2. Go to Tools menu -> Script Editor...
3. Click Spreadsheet
4. Copy the text from this file and paste it into the Google script editor.
5. Save and close the script editor.
6. Click on a cell A1 in the Spreadsheet (or any cell)
7. Enter in the cell the formula:
=cfdbdata("site_url", "form_name", "user", "password")
Where the parameters are (be sure to quote them):
site_url: the URL of you site, e.g. "http://www.mywordpress.com"
form_name: name of the form
user: your login name on your WordPress site
pwd: password
*/

/**
* Use this function in your spreadsheet to fetch saved form data from your WordPress Site
* @param {string} site_url your top level WordPress site URL
* @param {string} form_name name of the WordPress form to fetch data from
* @param {string} user login name to your WordPress site. User must have permission to view form data
* @param {string} password WordPress site password. If your site_url is "http" and not "https" then
* beware that your password is being sent unencrypted from a Google server to your WordPress server.
* Also beware that others who can view this code in your Google Spreadsheet can see this password.
* @param "option_name1", "option_value1", "option_name2", "option_value2", ... (optional param pairs).
* These are CFDB option such as "filter", "name=Smith", "show", "first_name,last_name"
* These should come in pairs.
* @returns {*} Your WordPress saved form data in a format suitable for Google Spreadsheet to display.
* String error message if there is an error logging into the WordPress site
* @customfunction
*/
function cfdbdata(site_url, form_name, user, password /*, [option_name, option_value] ... */) {
var param_array = [];
param_array.push("action=cfdb-login");
param_array.push("username=" + encodeURI(user));
param_array.push("password=" + encodeURI(password));
param_array.push("cfdb-action=cfdb-export");
param_array.push("enc=JSON");
param_array.push("format=array");
param_array.push("form=" + encodeURI(form_name));

var args = arg_slice(arguments, 4);
args = process_name_value_args(args);
param_array = param_array.concat(args);

return fetch_json_url(site_url, param_array);
}

function fetch_json_url(site_url, param_array) {
var url = site_url + "/wp-admin/admin-ajax.php";
var payload = param_array.join("&");
var response = UrlFetchApp.fetch(url, { method: "post", payload: payload });
var content = response.getContentText();
if (content.indexOf("<strong>ERROR") == 0) {
// If error message is returned, just return that as the content
return content;
}
// Logger.log(content); // For Debugging
return JSON.parse(content);
}

/**
* @deprecated for backward compatibility. Use cfdbdata() instead.
*/
function CF7ToDBData(site_url, form_name, search, user, password) {
if (search != "") {
return cfdbdata(site_url, form_name, user, password, "search", search);
}
return cfdbdata(site_url, form_name, user, password);
}

/**
* "slice" function for varargs Argument object
* @param args Argument object
* @param position int > 0 indicating the slice position
* @returns {Array} of args from the slide index to the end.
* Returns empty array if slice position exceeds length of args
*/
function arg_slice(args, position) {
var array = [];
if (args.length > position) {
for (var i = position; i < args.length; i++) {
array.push(args[i]);
}
}
return array;
}

/**
* Converts array like ['a', '1', 'b', '2'] to ['a=1', 'b=2']
* where each value is made to be URI-encoded.
* Purpose of this is to transform and array of name,value arguments
* into HTTP GET/POST parameters
* @param array Array like ['a', '1', 'b', '2']
* @returns {Array} like ['a=1', 'b=2'].
* where each value (a, 1, b, 2) are URL-Encoded
* If there is an odd number of arguments then the last one is dropped
* (expecting pairs of name,value)
*/
function process_name_value_args(array) {
var name_value_array = [];
var flag = true;
var name = null;
for (var i = 0; i < array.length; i++) {
if (flag) {
name = array[i];
} else {
name_value_array.push(encodeURI(name) + "=" + encodeURI(array[i]));
}
flag = !flag;
}
return name_value_array;
}


Keith Andersen

unread,
Feb 8, 2024, 5:19:46 AM2/8/24
to google-apps-sc...@googlegroups.com

Try re-entering the parameters paying attention to spelling and spaces.

That's All I can think of.


Andrew Apell

unread,
Feb 8, 2024, 5:43:00 AM2/8/24
to Google Apps Script Community
I see 5 functions. Which one is throwing the error?

Emerson Maia

unread,
Feb 8, 2024, 7:06:28 AM2/8/24
to google-apps-sc...@googlegroups.com

Good morning, I made some changes to the code and see if that works for you.

const cfdbdata = (siteUrl, formName, user, password, ...options) => {
    // Preparação dos parâmetros básicos para a requisição
    const params = [
      "action=cfdb-login",
      `username=${encodeURIComponent(user)}`,
      `password=${encodeURIComponent(password)}`,
      "cfdb-action=cfdb-export",
      "enc=JSON",
      "format=array",
      `form=${encodeURIComponent(formName)}`
    ];
 
    // Processamento de opções adicionais, se houver
    const additionalParams = processNameValueArgs(options);
    const allParams = [...params, ...additionalParams];
 
    // Realiza a requisição e retorna o resultado
    return fetchJsonUrl(siteUrl, allParams);
  }
 
  const fetchJsonUrl = (siteUrl, params) => {
    const url = `${siteUrl}/wp-admin/admin-ajax.php`;
    const payload = params.join("&");
    const response = UrlFetchApp.fetch(url, { method: "post", payload });
    const content = response.getContentText();
 
    // Verifica se a resposta é um erro
    if (content.startsWith("<strong>ERROR")) {
      return content; // Retorna a mensagem de erro diretamente
    }
 
    // Caso contrário, tenta parsear o JSON
    return JSON.parse(content);
  }
 
  const cf7ToDbData = (siteUrl, formName, search, user, password) =>{
    // Mantém compatibilidade com chamadas anteriores
    return search !== "" ?
      cfdbdata(siteUrl, formName, user, password, "search", search) :
      cfdbdata(siteUrl, formName, user, password);
  }
 
  const argSlice = (args, position) => {
    // Utiliza a função slice de Array para simplificar
    return Array.prototype.slice.call(args, position);
  }
 
  const processNameValueArgs = array => {
    const nameValuePairs = [];
    for (let i = 0; i < array.length; i += 2) {
      // Assume que a array tem um número par de elementos
      if (array[i + 1] !== undefined) {
        nameValuePairs.push(`${encodeURIComponent(array[i])}=${encodeURIComponent(array[i + 1])}`);
      }
    }
    return nameValuePairs;
  }
  
codehelpusa.png

Gilles

unread,
Feb 10, 2024, 12:04:59 AM2/10/24
to Google Apps Script Community
Thanks for trying to help but nothing explained the error I'm seeing. There is nothing wrong with the script itself.

Emerson Maia

unread,
Feb 10, 2024, 12:11:52 AM2/10/24
to google-apps-sc...@googlegroups.com
The [object Object] error often occurs in JavaScript when we try to convert an object to a string directly without proper serialization. In the case of your script that interacts with a WordPress instance to obtain form data, the error may be related to the way the result of the fetch_json_url function or the HTTP request response is handled.
maybe the error is here
function fetch_json_url(site_url, param_array) {
    var url = site_url + "/wp-admin/admin-ajax.php";
    var payload = param_array.join("&");
    var options = { method: "post", payload: payload };
    var response = UrlFetchApp.fetch(url, options);
    var content = response.getContentText();
   
    // Verifica se a resposta é um erro antes de tentar parsear como JSON
    if (response.getResponseCode() !== 200 || content.indexOf("<strong>ERROR") === 0) {
        Logger.log("Erro na requisição: " + content);
        return "Erro ao obter dados: " + content;
    }
   
    try {
        var jsonData = JSON.parse(content);
        return jsonData;
    } catch (e) {
        Logger.log("Erro ao analisar JSON: " + e.toString());
        return "Erro ao analisar resposta JSON.";
    }
}

Gilles

unread,
Feb 10, 2024, 12:14:17 AM2/10/24
to Google Apps Script Community
Thank for your response. The issue has nothing to do with the fetch. `[object Object]` is what I get for the arguments when the script is called, which makes no sense.
That is `site_url` is set to `[object Object]` and the other ones are `undefined`.

PS: I am a JS developer by trade.

Emerson Maia

unread,
Feb 10, 2024, 12:21:27 AM2/10/24
to google-apps-sc...@googlegroups.com
Can you send a print of the error?


Gilles

unread,
Feb 10, 2024, 12:24:16 AM2/10/24
to Google Apps Script Community
Here:
Exception: Invalid argument: http://[object%20Object]/wp-admin/admin-ajax.php at fetch_json_url(Code:75:32) at cfdbdata(Code:69:12)

As you can see, `site_url` is replaced by `[object Object]` converted into a URL-safe string but that is not what I passed in when calling the script.

Emerson Maia

unread,
Feb 10, 2024, 12:38:47 AM2/10/24
to google-apps-sc...@googlegroups.com
The problem occurs because site_url, which should be a string, is somehow being treated as an object ([object Object]). This can happen if the cfdbdata function is called with incorrect arguments or if there is data manipulation that turns the site_url into an object before reaching the fetch_json_url function.
Check the cfdbdata Function Call: Make sure site_url is passed correctly as a string. For example, if you are calling cfdbdata somewhere in your code, make sure the website URL is being passed as a string literal or a variable that contains a string.
Add a log line immediately before URL construction to check the value of site_url

console.log("Site URL: ", site_url); // Verifica o valor de site_url var url = site_url + "/wp-admin/admin-ajax.php";
Correct Call
cfdbdata("https://www.mywordpresssite.com", "myFormName", "myUsername", "myPassword");

I'm talking about a cell phone with a low battery


Andrew Apell

unread,
Feb 10, 2024, 12:41:03 AM2/10/24
to Google Apps Script Community
Try wrapping JSON.stringify() around "site_url" and see what happens.

Gilles

unread,
Feb 10, 2024, 12:43:29 AM2/10/24
to Google Apps Script Community
I just copied/pasted the cell content in the spreadsheet and it is somehow working again. Such non-sense and such a waste of time.

Andrew Apell

unread,
Feb 10, 2024, 12:50:57 AM2/10/24
to Google Apps Script Community
Hahaha... when I typed my last answer, I was actually laughing. I was very sure that the answer would very simple.
However, if it happened once, it will happen again. Ensuring that site_url is properly handled will be your best solution.

Gilles

unread,
Feb 10, 2024, 12:55:30 AM2/10/24
to Google Apps Script Community
Seems like a Google Sheets bug to me.

Edward Wu

unread,
Feb 12, 2024, 2:08:33 PM2/12/24
to google-apps-sc...@googlegroups.com
Swing in the dark...when you typed in/pasted in the url in the Google Sheet cell, are you hitting return or tab? Hitting tab might autoconvert a url into a "chip", which messes up all scripts trying to extract data from that cell, since Chips aren't Google Apps Script compatible yet.


Sophia willsons

unread,
Dec 31, 2025, 10:54:19 AM (2 days ago) 12/31/25
to Google Apps Script Community
You can use following website to conver json to excel or csv. 

Reply all
Reply to author
Forward
0 new messages