How to continue executing code after return - javascript

I'm writing a short program using Google Apps Script that understands certain answers that a user inputs into a form then executes a few things.
At the moment my code takes too long to execute and the form response page is just an error - but it does actually do everything in the background.
What I really want to do is return the response for the function earlier, then continue executing the rest of the code - but I know that is impossible. Any ideas?
function doPost(e) {
//get details from form
var json = e.postData.contents;
var obj = JSON.parse(json)
var answers = getAnswers(obj);
//do a few things...
var parentID = createParent(answers);
import(answers);
textOutput = ContentService.createTextOutput('Form Success! you can log
in with ' + answers.username + ' and password Test1234')
return textOutput
}

Related

sending multiple ajax requests not getting expected repsonse

so i have a javascript function that submits individual submissions from a form to a phpfile (processFeedback.php) that adds each submission to an array. then once the array is filled the array is passed back to the ajax callback (i think that's the proper terminology). if the array is passed back then the array gets passed to another php file (insertFeedback.php) that will insert the data into the database accordingly.
the entire site and all the scripts work perfectly, as in the array is getting filled and passed back to the ajax call correctly. but i'm getting an error message on the (insertFeedback.php) file call. as of right now the insertFeedback.php file does nothing but insert my database connect file. there is no return or anything being done on this page. i have tried several options, setting various arrays and json_encoding them with the same response every time. but i can't get a set answer as to why as the jqxhr.error sends me to a jquery fuction that i do not as of yet understand, and there is no jqxhr.responseText (both of which i use regularly for debugging.
here's my function:
function prepareData(cont, sect) {
var sentData = {'choice': cont, 'section': sect};
var addSession = $.post('processFeedback.php', sentData, null, 'json');
addSession.done(function (fbData) {
console.log('success: ' + fbData);
action = fbData.action;
if (fbData.status) {
receivedData = fbData.data;
console.log('receivedData.age: ' + receivedData.age);
var insertData = $.post('insertFeedback.php', receivedData);
insertData.done(function(insertData) {
console.log('from insert page: ' + insertData);
});
insertData.fail(function(noInsertData) {
console.log('failed at insert page: ' + noInsertData);
})
}
if (!fbData.status) {
console.log('form not complete yet');
}
eval(action);
});
addSession.fail(function (a, b, c) {
console.log('failure: ' + a.reponseText);
});
}
i have been starting at this code for hours, so i know this is going to be a painstakingly simple answer. most likely just messing up my variables somewhere along the way. but any help with why the insertData function keeps failing.

Odd occurrence in using app.use(parseExpressRawBody())

Maybe this is simple, maybe this is a bug on Parse - would like to know if anyone has had the same problem and a possible solution.
What I'm trying to do:
I'm sending a JSON request from an app called FormEntry to my Parse app
The body comes in like this: json={"someLabel" : "someValue"}
I would like to take the entire body and create a Parse.Cloud.httpRequest over to Zapier to perform some functions.
Now, the problem seems to be this:
On random occasions (i.e. I have no idea why), the body is sent (as shown by the logs) where there is a trailing comma at the end of the last pair in the JSON object. e.g. like this json={"lastLabel" : "lastValue",}
The number of elements in 'normal' and 'incorrect' objects seem to be the same, so it's simply just another comma added. And I have no idea why.
My setup:
Using app.use(parseExpressRawBody()); only and not the standard app.use(express.bodyParser()); which doesn't provide access to the raw body.
Because parseExpressRawBody converts the body to a buffer I need to turn it back into a string to send it in the HTTP request in a meaningful way. Therefore I use: var body = req.body.toString();
When logging this var to the Parse console it looks to be format back from the buffer fine.
And that's about it. Nothing complex going on here but a real annoying bug that I just haven't found a sensible way of understanding. Would SUPER appreciate anyone who has seen this before or who could point me in a direction to focus on.
Just an update on this. Not a solution that answers why there is malformed JSON but a hack to get the right result.
The purpose of the HTTP request was to point over to Zapier so I wrote a Zapier script that would deal with the malformed JSON. Added here for anyone else who needs it.
"use strict";
var Zap = { newSubmission_catch_hook: function(bundle) {
var body = bundle.request.content;
var cleanTop = body.substring(5,body.length);
var cleanChar = cleanTop.length;
var condition = cleanTop.substring(cleanChar-2,cleanChar);
function testCase(condition,cleanTop) {
if (condition != ",}"){
console.log("Everything is fine, returning JSON");
return cleanTop;
}
else {
console.log("Nope! We have an error, cleaning end");
var cleanEnd = cleanTop.substr(0,cleanChar-2) + '}';
console.log("The object now ends with: " + cleanEnd.substr(-10));
return cleanEnd;
}
}
var newBody = JSON.parse(testCase(condition,cleanTop));
return newBody;
}
};

Waiting till call back completes Node.js

My situation is like this, I have a server like this and inside I am calling another callback function which gets multiple values:
var http = require('http');
var server = http.createServer(req,resp) {
var finalVal = "";
consumer.on('message',function(message) {
finalVal = message;
console.log(finalVal);
});
resp.end(finalVal);
});
My finalVal should display all the multiple values it fetches and send it as a response, but problem is it's sending only first value where as console.log displays all the values. I do understand that by the time consumer.on ends response would have committed. Can someone please help me how to handle this scenario since I'm very new to Node.js ? Currently due to heavy deadlines I don't have time to read full information about callbacks. But defnitely I would take time to learn about callbacks.
Edit: Here consumer.on calls multiple times till it fetches all the data from backend, I need to send all those data in a final response. I am using node-kafka to consume to kafka messages.
There must be an end event or something like that which tells that consumer has finished the message, you can use that
I am not sure what is consumer here, but in most of cases we go with something like bellow
var finalVal = '';
consumer.on('message',function(message) {
finalVal += message; // So on each message you will just update the final value
console.log(finalVal);
});
consumer.on('end',function(){ // And at the end send the response
resp.end(finalVal);
});

Jquery .get() result evaluation not working

I'm relatively new to javascript, but I've read lots of posts talking about Jquery .get and the need to use a callback function today... but I guess I'm still not doing it right. I have a function that 'gets' the result from a PHP page which accesses a MySQL table.
I've included alerts in my code so I can see that the page is called correctly and is returning the result I expect. If the file already exists in the database then the 'get' returns "exists" if the file is in the database but flagged as deleted 'get' returns "deleted" and if the file isn't in the database 'get' returns nothing.
However, when I place alerts inside the if(file_exists=="exists") statement they never get triggered. I even tried moving the entire evaluation section to another function and calling that function from inside the first. still no joy. docReplace never gets set to true and I never see the dialog asking if I want to replace it.
Please, some helpful suggestions?
<script type = "text/javascript" language = "javascript">
function docCheck(){
var attachfilepath = document.getElementById("AttachFile").value;
var docguid = document.getElementById("DocGuid").value;
//cut the file path down so just get the filename
attachfile = attachfilepath.substr(attachfilepath.lastIndexOf("\\")+1);
// Check to see if file exists.
$.get("Doc_Check.php", {guid:docguid, filename:attachfile}, function(file_exists){
alert(file_exists);
if(file_exists=="exists"){
if(confirm("The file \"" + attachfile +"\" already exists. Would you like to replace it?")){
document.getElementById('docReplace').value = "true";
}else{
return false;
}
}else if(file_exists == "deleted"){
document.getElementById('docReplace').value = "true";
}
});
var rreplace = document.getElementById('docReplace').value;
alert (attachfile);
alert (docguid);
alert (rreplace);
}
</script>

Javascript Error when updating client using AJAX call

I am trying to model a chat application on a browser(Firefox).Here I am trying to send the char inserted into a text area on one machine to another client and update its text area.
I am trying to send the key pressed on the client using AJAX calls. Below is the function call that I have written :
function returnKeyFromCode(code)
{
//Returns char code
};
function keyPress(e)
{
var textReplace = document.getElementById("textReplace");
var keyPressed = returnKeyFromCode(e.which) ;
textReplace.innerHTML = keyPressed;
var locationReplace = document.getElementById("location");
locationReplace.innerHTML = mainDoc.selectionStart;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){};
xmlhttp.open("POST","http://localhost:5000?key=" + keyPressed + "&pos=" +mainDoc.selectionStart +"&revno=1&param=EOS",true);
xmlhttp.send("Stuff");
};
At the client side, when the char is received the following error is displayed on the fire bug console:
'0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]' .
Before sending the data, a persistent connection is being set up between client ans server using another Ajax call.
It looks like you've edited some of your code before posting this question, so I can only speculate, but based on the error, i'd guess at some point you're sending null to this function: xmlhttp.send("Stuff");
Try doing a null check on the data before you send it, or possibly make sure whatever starts the send process is in a document ready, so that you're not trying to grab data from an undefined text element.

Categories