Previously, I was able to send data from a HTML Form to Google Form (Responses Spreadsheet) using ajax
. Here's the code.
Ajax Code
function postContactToGoogle() {
var email = $('#emailtosubscribe').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/[key]/formResponse",
data: {
"entry_1064445353": email
},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
window.location.reload();
},
200: function() {
window.location.reload();
}
}
});
}
Now, I am trying to do the same in Unity using UnityWebRequest
. Here's my code
Unity Code
public class SendToGoogle : MonoBehaviour {
public GameObject email;
private string Email;
[SerializeField]
private string BASE_URL = "https://docs.google.com/forms/d/e/[key]/formResponse";
IEnumerator Post(string json) {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(json);
using (UnityWebRequest www = new UnityWebRequest(BASE_URL, UnityWebRequest.kHttpVerbPOST)) {
UploadHandlerRaw uH = new UploadHandlerRaw(bytes);
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
www.uploadHandler = uH;
www.downloadHandler = dH;
www.SetRequestHeader("Content-Type", "application/json");
yield return www.Send();
if (www.isError) {
Debug.Log(www.error);
} else {
Debug.Log(www.ToString());
Debug.Log(www.downloadHandler.text);
}
}
}
public void Subscribe() {
Email = email.GetComponent<InputField>().text;
var n = new JSONObject();
n["entry_1064445353"] = Email;
string json = n.ToString();
Debug.Log(Email);
StartCoroutine(Post(json));
}
}
Now when I try to submit email from the Scene, time stamp is created in the spreadsheet but the email is not saved. I am doubtful on www.SetRequestHeader("Content-Type", "application/json");
, as in ajax
I am using xml
as datatype
with dataType: "xml"
.
Moreover, I also tried sending just string
without changing it to JSONObject
and changing Content-Type
on SetRequestHeader
to xml
.