Problem with Detection in real time using - Yolov5 & Django & React - reactjs

I am trying to get the percent of detection that showing in the video (when having a detection) that I am Streaming,
to the client and display it on a table for every moment and in the same second that detection happening, but for now I get only a little part of the data and it’s happening after a few seconds
I using Django to stream a video with, detection using yolov5 , and I display the video in the client using react.
my problem is that I create a function that give me the percent of the detection for my custom object when it's show in the video.
I want to use this data and display beside the video.
i need that every time and in the same moment ,that have a detect I’ll get this data and display It.but now it’s not work for me, it’s only send the data and display it for one/two times , and after few seconds . I’m sure that I have some problem with detection() function and maybe with the detection_percentage()
but unfortunately I am not found a way to solve it
views.py
def stream():
cap = cv2.VideoCapture(source)
model.iou=0.5
model.conf=0.15
while (cap.isOpened()):
ret, frame = cap.read()
if not ret:
print("Error: failed to capture image")
break
results = model(frame,augment=False,size=640)
for i in results.render():
data=im.fromarray(i)
data.save('demo.jpg')
det = results.pred[0]
annotator = Annotator(frame, line_width=2, pil=not ascii)
im0 = annotator.result()
image_bytes = cv2.imencode('.jpg', im0)[1].tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + image_bytes + b'\r\n')
cap.release()
cv2.destroyAllWindows()
def detection():
model.iou=0.5
model.conf=0.15
cap = cv2.VideoCapture(source)
while (True):
ret, frame = cap.read()
if not ret:
print("Error: failed to capture image")
break
results = model(frame, augment=False,size=640)
det = results.pred[0]
if det is not None and len(det):
xywhs = xyxy2xywh(det[:, 0:4])
confs = det[:, 4]
clss = det[:, 5]
outputs = deepsort.update(xywhs.cpu(), confs.cpu(), clss.cpu(), frame)
for j, (output, conf) in enumerate(zip(outputs, confs)):
label = f'{conf:.2f}'
print(label)
return label
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
p1 = Process(target = stream)
p2 = Process(target = detection)
p1.start()
p2.start()
p1.join()
p2.join()
def video_feed(request):
return StreamingHttpResponse(stream(), content_type='multipart/x-mixed-replace; boundary=frame')
def detection_percentage(request):
return HttpResponse(detection())
client side
const Streamvideo = () => {
const urlStream = "http://127.0.0.1:8000/video_feed";
const urlDetaction="http://127.0.0.1:8000/detection_percentage";
const [data, setData] = useState("None");
const [children, setChildren] = useState([]);
const getPrecentOfDetection = async () => {
try {
const resp = await axios.get(urlDetaction);
console.log(resp.data);
setData(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
useEffect(() => {
getPrecentOfDetection ();
}, []);
useEffect(() => {
setChildren((prev) => [
...prev,
<div>
<h6>Detection:{data}</h6>
<h6> Cureent Time:{showTime}</h6>
</div>,
]);
}, [data, showTime]);
return (
<div>
<img className={css.img} src={urlStream} alt="" />
<div>
<div className={css.cat}>{children}</div>
</div>
</div>
);
};
export default Streamvideo;

Related

How do I remove the delay between pushing the button and the first sound?

I made a metronome inspired by the famous Chris Wilson's article using React, Hooks, and the Web Audio API.
The metronome works but there's a delay between the moment I hit 'play' and the sound itself.
This is clearly noticeable if the BPM is very low (e.g. 40 BPM).
At first, I thought I needed to isolate the logic from the UI rendering using a Worker but now I start to think it's something else.
I think in the timer function I need an else calling sound with a 0 value.
But I haven't found a solution yet.
Does anybody have an idea what's wrong and how to fix it?
Thanks!
import { useState } from 'react';
let ac;
let lastNote = 0;
let nextNote = 0;
let engine;
function App() {
const [isPlaying, setIsPlaying] = useState(false);
const [bpm] = useState(40);
const oneBeatInSeconds = 60000 / bpm / 1000;
ac = new AudioContext();
const sound = (ac: AudioContext, time: number, dur: number) => {
// creates the sound, connects it and decides when it starts and stops
const osc = ac.createOscillator();
osc.connect(ac.destination);
osc.start(time);
osc.stop(time + dur);
};
const timer = () => {
// Calculates how long it was in ms from loading the browser to clicking the play button
const diff = ac.currentTime - lastNote;
// Schedules the next note if the diff is larger then the setInterval
if (diff >= oneBeatInSeconds) {
nextNote = lastNote + oneBeatInSeconds;
lastNote = nextNote;
sound(ac, lastNote, 0.025);
}
ac.resume();
};
if (isPlaying) {
// If the metronome is playing resumes the audio context
ac.resume();
clearInterval(engine);
engine = setInterval(timer, oneBeatInSeconds);
} else {
// If the metronome is stopped, resets all the values
ac.suspend();
clearInterval(engine);
lastNote = 0;
nextNote = 0;
}
const toggleButton = () =>
isPlaying === true ? setIsPlaying(false) : setIsPlaying(true);
return (
<div className="App">
<div className="Bpm">
<label className="Bpm_label" htmlFor="Bpm_input">
{bpm} BPM
</label>
<input type="range" min="40" max="200" step="1" value={bpm} />
</div>
<button type="button" className="PlayButton" onClick={toggleButton}>
{!isPlaying ? 'play' : 'stop'}
</button>
</div>
);
}
export default App;
If you want to play the first beep at once you can directly schedule it in near future without using setInterval. Additionally, it is better to run the function, that schedules the next beep, by setTimeout each time instead of using setIntervall. This makes sure that the beat always is aligned to the time frame that is used by the AudioContext. Here is a simplified example based on your code:
import React, { useEffect, useState } from 'react';
const duration = 0.1;
const bpm = 40;
const shortDelta = 0.01;
const oneBeatInSeconds = 60000 / bpm / 1000;
let ac;
let nextBeep = 0;
function scheduleNextBeep() {
let thisBeep = nextBeep;
if (thisBeep > 0) {
// schedule the next beep short before it shall be played
nextBeep += oneBeatInSeconds;
setTimeout(scheduleNextBeep, (nextBeep - ac.currentTime) * 1000 - shortDelta);
// schedule this beep
const osc = ac.createOscillator();
osc.connect(ac.destination);
osc.start(thisBeep);
osc.stop(thisBeep + duration);
}
}
function App() {
const [isPlaying, setIsPlaying] = useState(false);
useEffect(() => {
ac = new AudioContext();
}, []);
function toggleButton() {
if (isPlaying) {
setIsPlaying(false);
nextBeep = 0;
} else {
setIsPlaying(true);
// schedule the first beep
nextBeep = ac.currentTime + shortDelta;
scheduleNextBeep();
}
}
return (
<div className="App">
<div className="Bpm">{bpm} BPM</div>
<button type="button" onClick={toggleButton}>
{isPlaying ? 'stop' : 'play'}
</button>
</div>
);
}
export default App;
Update 07/15/2022
As discussed in the comments you can improve the quality of the "beep" sound by using a nice sample wav instead of the OscillatorNode. If you definitely need the oscillator for some reason you can apply an envelope to the beep like this:
function scheduleNextBeep() {
let thisBeep = nextBeep;
if (thisBeep > 0) {
// schedule the next beep short before it shall be played
nextBeep += oneBeatInSeconds;
setTimeout(scheduleNextBeep, (nextBeep - ac.currentTime) * 1000 - shortDelta);
// prepare this beep
const oscNode = ac.createOscillator();
const gainNode = ac.createGain();
oscNode.connect(gainNode);
gainNode.connect(ac.destination);
// set envelope of beep
gainNode.gain.value = 1.0;
gainNode.gain.setValueAtTime(1.0, thisBeep + duration * 0.7);
gainNode.gain.exponentialRampToValueAtTime(0.00001, thisBeep + duration);
// schedule this beep
oscNode.start(thisBeep);
oscNode.stop(thisBeep + duration);
}
}
This a minor bug,
one possible solution could be thinking about setInterval a bit.
setInterval function runned with a delay ..
You can try to call your timer function outside the setInterval .
And for more information you can read this.
setinterval-function-without-delay-the-first-time
In short answer what I mean is that if you try to use setInterval with 200 ms interval , the first time that your function called is not exactly 200 ms :)
Nice solution:
(function foo() {
...
setTimeout(foo, delay);
})();

Post a message from iframe in React

I have trouble about sending message from cross-domain iframe in React. I read many articles, most of them are about sending message to iframe.
The issue is that it didn't show any error message in the page that embed the iframe , and when I go to the see the page that I embed, it did show a error message.
Scene.js:230 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://thewebsite.com') does not match the recipient window's origin ('https://mywebsite').
so I can't tell if I the message have been sent successfully or not.
Here is my code :
confirm = () => {
const { homeId, correctData } = this.state
const form = new FormData();
//process data
form.append('scene_id', homeId)
form.append('material_id', correctData[0].id)
form.append('material_img', correctData[0].component_img)
const obj = JSON.parse(JSON.stringify(form));
//
//way 1
parent.postMessage(obj, '*')
//way 2
parent.postMessage(obj, 'https://www.thewebsite.com/pro_wall.html')
//way 3
window.frames.postMessage(obj, '*')
//way 4
window.top.postMessage(obj, '*')
//way 5
const targetWindow = window.open('https://www.thewebsite.com/pro_wall.html')
setTimeout(() => {
targetWindow?.postMessage(obj, '*')
}, 3000)
}
Sorry for writing too many ways to post message, Just want to make sure I tried every possibility.
After few tries, I got positive feedback from the client. They got data. This is my code I wrote eventually.
confirm = () => {
const { homeId, correctData } = this.state
const formData = new FormData();
formData.append('scene_id', homeId)
formData.append('material_id', correctData[0]?.id)
formData.append('material_img', correctData[0]?.component_img)
var object = {};
formData.forEach((value, key) => {object[key] = value});
var json = JSON.stringify(object);
parent.postMessage(json, `https://www.thewebsite.com/pro_wall.html`)
}
and I saw the code at client's side from web devTool, it looks like this,
<script>
window.addEventListener("message", receivewall, false);
function receivewall(event){
var origin = event.origin;
if(origin == 'https://mywebsite'){
var params = JSON.parse(event.data);
$('#result').html($.param(params));
// console.log(params);
}
// $('#result').html(data);
}
function getQueryVariable(query) {
var vars = query.split('&');
var params = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return params;
}
</script>

Add tracks or create new Stream ending with Media Recorder ending up corrupted file

this is the last post which answer where my goal is in developing my project: RecordRTC with sending video chunks to server and record as webm or mp4 on server side. After recording the screen sharing stream, I decide to move forward to add video tracks to screen sharing. There are two ways for me to do it, by using addTracks function or create a new stream with contain the video from the screen sharing and audio from my media. However, both of them resulting me in the previous error in the aforementioned link: corrupted video.
FYI: Here is the link for anyone who wants to read more about Media Recorder: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder
P/S: If you encourage me on switching to webRTC again, I would be appreciated if you could help me in solving the issue - the file ends up corrupted when using webRTC - in aforementioned link?
Here is the code from my backend and frontend:
Client code:
startMedia = ()=>{
this.setState({mediaState:"pending"})
navigator.mediaDevices.getDisplayMedia({video: true}).then( async (screenSharingStream)=>{
console.log(MediaRecorder.isTypeSupported('video/webm; codecs=vp8,opus'))
const socketIO = io.connect(baseURL,{query: {candidateID: this.candidateID,roundTest:this.roundTest }})
const mediaStream = await navigator.mediaDevices.getUserMedia({video:true,audio:true}).catch(e => {throw e});
const mediaReCorderoptions = {
videoBitsPerSecond : 128000,
audioBitsPerSecond:128000,
mimeType : 'video/webm; codecs=vp8,opus'
}
const [videoTrack] = screenSharingStream.getVideoTracks();
const [audioTrack] = mediaStream.getAudioTracks();
if (audioTrack && videoTrack)
videoTrack.addTrack(audioTrack)
const stream = new MediaStream([videoTrack, audioTrack]);
this.socketRef.current = socketIO;
this.mediaStream = mediaStream
this.screenSharingStream = stream
this.candidateVideoRef.current.srcObject = this.mediaStream;
this.mediaRecorder = new MediaRecorder(this.screenSharingStream,mediaReCorderoptions)
this.mediaRecorder.ondataavailable = function(event){
if (event && event.data.size>0){
const reader = new FileReader();
reader.onload = function(){
const dataURL = reader.result;
console.log('van chay')
const base64EncodedData = dataURL.split(',')[1];
//console.log(buffer)
socketIO.emit('SEND BLOB',base64EncodedData)
}
reader.readAsDataURL(event.data)
}
}
this.mediaRecorder.start(1000)
this.setState({mediaState:this.mediaRecorder.state})
}).catch(err=>{
console.log(err.name)
switch(err.name){
case 'NotAllowedError':
message.error('Candidate does not allow!!')
this.setState({mediaState:"Aborting"})
break;
default:
message.error('System Error. Please contact us!')
this.setState({mediaState:"Aborting"})
break;
}
})
}
stopMedia = () =>{
if (this.mediaStream){
this.mediaStream.getTracks().forEach((track)=>{
if (track.readyState==='live') {
track.stop()
this.candidateVideoRef.current.style.display='none';
}})
}
if (this.screenSharingStream) {
this.mediaRecorder.stop()
this.setState({mediaState:this.mediaRecorder.state})
}
}
Server code:
socket.on("SEND BLOB",chunk=>{
try {
//if (chunk instanceof Buffer){
const fileExtension = '.webm'
const dataBuffer = new Buffer(chunk, 'base64');
const fileStream = fs.createWriteStream(path.join(__dirname,'./videos/candidate/',candidateID + '-' + roundTest + fileExtension), {flags: 'a'});
fileStream.write(dataBuffer);
}
catch(e){
console.log(e)
}
})

Tensorflow.js prediction result doesn't change

I trained my model with Google Teachable Machines (Image) and inclueded the model into my Ionic Angular app. I loaded the model successfully and used the camera preview for predicting the class which is shown in the image from the camera.
The picture which is displayed in the canvas changes properly but the predict()-method returns the same result for every call.
import * as tmImage from '#teachablemachine/image';
...
async startPrediction() {
this.model = await tmImage.load(this.modelURL, this.metadataURL);
this.maxPredictions = this.model.getTotalClasses();
console.log('classes: ' + this.maxPredictions); //works properly
requestAnimationFrame(() => {
this.loop();
});
}
async loop() {
const imageAsBase64 = await this.cameraPreview.takeSnapshot({ quality: 60 });
const canvas = document.getElementById('output') as HTMLImageElement;
//image changes properly, I checked it with a canvas output
canvas.src = 'data:image/jpeg;base64,' + imageAsBase64;
const prediction = await this.model.predict(canvas);
for (let i = 0; i < this.maxPredictions; i++) {
const classPrediction =
prediction[i].className + ': ' + prediction[i].probability.toFixed(2);
//probability doesn't change, even if I hold the camera close over a trained image
}
requestAnimationFrame(() => {
this.loop();
});
}
The prediction result is e.g.: class1 = 0.34, class2 = 0.66 but doesn't change.
I hope you could help me to find my bug, thanks in advance!
The image has probably not yet been loaded before you are calling the prediction model. It has been discussed here and there
function load(url){
return new Promise((resolve, reject) => {
canvas.src = url
canvas.onload = () => {
resolve(canvas)
}
})
}
await load(base64Data)
// then the image can be used for prediction

Submit form(ReactJS) to Google Spreadsheet - change the message validation

I want to register data in a Google Sheet from a ReactJS form (2 fields if the user has possible suggestion or comments).
This is my feedback form in React :
import React,{useState,useEffect} from 'react';
import './App.css';
const formUrl = 'https://script.google.com/macros/s/AK.../exec'
export default function FrmTable(){
const [loading,setLoading] = useState(false)
return(
<div className="section-form">
<form name="frm"
method="post"
action={formUrl}
>
<div className="form-elements">
<div className="pure-group">
<label className="pure-group-label">Suggestion content pdf</label>
<input id="Suggestion content pdf" name="Suggestion content pdf" className="pure-group-text"
type="text"
/>
</div>
<div className="pure-group">
<label className="pure-group-label" >Comments</label>
<textarea id="Comments" name="Comments" rows="10" className="pure-group-text"
placeholder=""
maxLength="1000"
></textarea>
</div>
</div>
<p className="loading-txt">{loading == true ? 'Loading.....' : ''}</p>
<div className="pure-group pure-group-btn">
<button className="button-success pure-button button-xlarge btn-style" >Send</button>
</div>
</form>
</div>
)
}
The GSheet script in order to register the suggestion content and comments :
var SHEET_NAME = "Feedback";
// 2. Run > setup
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp(Date)' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Everything works fine I can register the 2 fields(suggestion and comment) in the GSheet but I would like to have another view after submiting
I've followed some tutorials because I'm new into React. At the end after submiting you are sent to script.googleusercontent.... because in the GSheet script we have this code
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
I want just to show a simple message like a popup in order to say the submit form is ok. Any idea is welcomed :) thank you very much.
New Edit : I've changed my code (React + Google Script) but I have an CORB blocked cross-origin.
import React,{useState,useEffect} from 'react';
import './App.css';
const formUrl = 'https://script.google.com/macros/s/AKfycbz4hMELOHff2Yd_ozpOid2cAWFSWPm_7AOD15OIeQRdYrocv0wa/exec'
export default function FrmTable(){
const jsonp = (url, callback) => {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
alert("Formulaire envoyé ");
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
document.body.appendChild(script);
}
const mySubmitHandler = (event) => {
event.preventDefault();
jsonp(formUrl + '?La+FAQ+en+question=' + encodeURIComponent(faqName), (data) => {
// alert(data);
});
event.target.reset();
}
// const { register, errors, required ,handleSubmit } = useForm();
const [loading,setLoading] = useState(false)
const [faqName,setFaqName] = useState('')
const myChangeHandler1 = (event) => {
setFaqName(event.target.value);
}
return(
<div className="section-form" >
<form name="frm"
method="post"
onSubmit={mySubmitHandler}
>
<div className="form-elements">
<div className="pure-group ">
<label className="pure-group-label">La FAQ en question </label>
<input name="FAQ en question" className="pure-group-text"
type="text" onChange={myChangeHandler1}
/>
</div>
</div>
<input type='submit' />
</form>
</div>
)
}
The Google Script :
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
//return handleResponse(e);
}
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp(Date)' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
var callback = e.parameter.callback;
// return json success results
// return ContentService
// .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
// .setMimeType(ContentService.MimeType.JSON);
return ContentService.createTextOutput(callback+'('+ JSON.stringify({"result":"success", "row": nextRow})+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
} catch(error){
// if error return this
//return ContentService
// .createTextOutput(JSON.stringify({"result":"error", "error": e}))
// .setMimeType(ContentService.MimeType.JSON);
var callback = e.parameter.callback;
return ContentService.createTextOutput(callback+'('+ JSON.stringify({"result":"error", "error": error})+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
I would like to propose the following 2 patterns.
Modification points:
In the current stage, there is no getPublicLock().
In your shared Spreadsheet, there is only one sheet of Sheet2. But at var SHEET_NAME = "Feedback";, no sheet name is used. By this, var sheet = doc.getSheetByName(SHEET_NAME); is null and an error occurs at var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0].
At formUrl + "&Commentaires=" + encodeURIComponent(faqComment) in react side, in this case, the endpoint becomes https://script.google.com/macros/s/###/exec&Commentaires=test?callback=jsonp_callback_###.
Pattern 1:
In this pattern, your script is modified and JSONP is used.
React side: App.js
From:
jsonp(formUrl + "&Commentaires=" + encodeURIComponent(faqComment), data => {
// alert(data);
});
To:
jsonp(formUrl + "?Commentaires=" + encodeURIComponent(faqComment), data => {
// alert(data);
});
Google Apps Script side:
When you want to use your shared Spreadsheet, please modify as follows.
From:
var lock = LockService.getPublicLock();
To:
var lock = LockService.getDocumentLock();
And,
From:
var SHEET_NAME = "Feedback";
To:
var SHEET_NAME = "Sheet2";
In this case, you can also modify the sheet name from Sheet2 to Feedback instead of modifying the script.
Pattern 2:
In this pattern, your script is modified and fetch is used instead of JSONP. Because when above script is used, I could confirm that there is sometimes the error related to CORS. So as another pattern, I would like to propose to use fetch. When fetch is used, I could confirm that no error related to CORS occurs.
React side: App.js
From:
export default function FrmTable() {
const jsonp = (url, callback) => {
var callbackName = "jsonp_callback_" + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
alert("Formulaire envoyé ");
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
var script = document.createElement("script");
script.src =
url + (url.indexOf("?") >= 0 ? "&" : "?") + "callback=" + callbackName;
document.body.appendChild(script);
};
const mySubmitHandler = event => {
event.preventDefault();
/* const request = new XMLHttpRequest();
const formData = new FormData();
formData.append("La FAQ en question", form.faqName);
formData.append("Suggestion contenu pdf", form.faqSuggest);
formData.append("Commentaires", form.faqComment);
request.open("POST", formUrl);
request.send(formData); */
jsonp(formUrl + "&Commentaires=" + encodeURIComponent(faqComment), data => {
// alert(data);
});
event.target.reset();
};
To:
export default function FrmTable() {
const mySubmitHandler = event => {
event.preventDefault();
fetch(formUrl + "?Commentaires=" + encodeURIComponent(faqComment))
.then(res => res.text())
.then(res => console.log(res))
.catch(err => console.error(err));
event.target.reset();
};
In this case, res.json() can be also used instead of res.text().
Google Apps Script side:
When you want to use your shared Spreadsheet, please modify as follows.
From:
var lock = LockService.getPublicLock();
To:
var lock = LockService.getDocumentLock();
And,
From:
var callback = e.parameter.callback;
return ContentService.createTextOutput(callback+'('+ JSON.stringify({"result":"success", "row": nextRow})+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
} catch(error){
var callback = e.parameter.callback;
return ContentService.createTextOutput(callback+'('+ JSON.stringify({"result":"error", "error": error})+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
} finally { //release lock
lock.releaseLock();
}
To:
return ContentService.createTextOutput(JSON.stringify({"result":"success", "row": nextRow})).setMimeType(ContentService.MimeType.JSON);
} catch(error){
return ContentService.createTextOutput(JSON.stringify({"result":"error", "error": error})).setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
And,
From:
var SHEET_NAME = "Feedback";
To:
var SHEET_NAME = "Sheet2";
In this case, you can also modify the sheet name from Sheet2 to Feedback instead of modifying the script.
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Class LockService

Resources