Can doPost() run itself? - javascript

function doPost(e) {
var msg= JSON.parse(e.postData.contents);
var shitText = msg.messaging[0].message.text;
var senderId = msg.messaging[0].sender_id;
Logger.log(e)
.
.
.
(do something)
}
I use doPost() smoothly.
But when I create the (e) objects to pass to it and try to run itself,
the syntax errors tells that
"It cannot load the contents properties of undefined".
Like picture show below.
Can't the doPost() run itself?
Or just to need post the data to it to do functions?
Thank you.

doPost() can run by itself without initializing the e variable in the parameter. I think the problem comes from the contents property in the JSON string, so you should look at it. It has a 's'.
Also you need to post the e variable here (which should be a nested JSON string), or we don't know what is wrong with the codes.
You can try and run this code, this will work. The example below showcases that you can initialize e variable inside a parameter to ensure that the function still work even when you call doPost() without any parameter.
function abc(e = '{\"sample\": {\"someitem\": {\"thesearecool\": [{\"neat\": \"wow\"},{\"neat\": \"tubular\"}]}}}'){
var msg= JSON.parse(e);
console.log(msg.sample.someitem.thesearecool[0].neat)
}
abc();
Edit: if you are using JS, don't use e as varriable, you will mistake it sometimes with (e) as event.

e in the Apps Script function doPost(e) stands for an event object which will only be initialized when the event takes place.
e.postData.contents are the contents of data obtained from a post request.
if you run the function manually, without a trigger event taking place - there are no post data contents linked to an event and this gives you the error.
If you just want to test your function manually, you need to use doPost() without the e and assign a value to your post data contents manually.

Related

Pass and use data from json to javascript

I have a javascript function that I am calling in a php page. I also added a json method to this function that pulls data from the database. Here's what it looks like:
$this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class]]);
$this->registerJs('restaurantReserve.init('. Json::encode($restaurant->workHours) .')');
As a result, at the end of the page, I get this data in the form:
restaurantReserve.init([{"id":86,"restaurant_id":1,"day":"Mon","open":"9.30","close":"14.30","created_at":"2022-02-22 10:56:15"}])
But I want to use this data in the javascript file itself, where the restaurantReserve function is located.
Because now I have to do it manually:
let json = [{"id":86,"restaurant_id":1,"day":"Mon","open":"9.30","close":"14.30","created_at":"2022-02-22 10:56:15"}]
How can I make json data come to javascript so that I can use it? To not write it by hand.
update
One of the answers came up to me, it was to add this line, which will globally declare this variable:
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
But it turns out that this variable is declared after the execution of the script of this restaurant-reserve.js file where this variable is used, and I don’t understand a little how to make it higher.
Here is my final code in php file:
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
$this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class]]);
$this->registerJs('restaurantReserve.init()');
And what I get as a result on the page, first comes the file, then this variable:
<script src="/js/restaurant-detail.js"></script>
<script src="/js/share.js"></script>
<script>jQuery(function ($) {
let json = [{"id"...}]
</script>
What can be done??
The second argument in registerJs is related to this issue.
That is, The second argument determines at which position the script should be inserted into the page. Possible values are:
View::POS_HEAD for head section.
View::POS_BEGIN for right after opening <body>.
View::POS_END for right before closing </body>.
View::POS_READY for executing code on the document ready event. This will automatically register jQuery and wrap the code into the appropriate jQuery code. This is the default position.
View::POS_LOAD for executing code on the document load event. Same as the above, this will also register jQuery automatically.
The first argument is the actual JS code we want to insert into the
page. It will be wrapped into a tag. The second argument
determines at which position the script should be inserted into the
page.
For scriptFiles you can also specify the place and time to load it. According to the dependencies and ....
It is better to refer to this link.
You may add following line in the code
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
Updating the answer after reading your comments and further queries.
You may pass second one more parameters to registerJs function.
View::POS_READY or View::POS_BEGIN
Like :
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';', View::POS_READY);

Sharing Data Between Javascript Files

I have a script that generates a JSON formatted string. I want to use the data contained in this string in another script. I'm not sure where to even start. I've thought about running both scripts from the same directory and somehow outputting the JSON data into a text file and then loading it into the second script but this seems like more of a workaround than an actual solution. Is it possible to somehow call the second script from the first and pass it the data? Much like passing data between functions in a single script?
FWIW I have tried simply combining the functions the two scripts perform into one, but this has caused me countless headaches with no progress. For simplicity sake I'd prefer to keep the functions performed by each script separate (apart from the obvious data sharing requirement!).
Any advice or a point in the right direction would be greatly appreciated.
If JSON data is less than 5 mb then you can use localStorage to save the output in browser.
In first js file:
function fOne(){
var jsonStr = ''; //insert some json data here
localStorage.setItem("myJson", JSON.stringify(jsonStr)); //save data
}
In your second js file:
function fTwo(){
if (localStorage.getItem("myJson") !== null) {
var passedJson = localStorage.getItem("myJson"); //get saved data anytime
}
}
It is hard to say without some code to reference but maybe just a global variable with a check if its null.
var myJsonString = null;
function one () {
var jsonString = "[]";
myJsonString = jsonString;
}
function two () {
//string not set so bail
if (myJsonString === null) { return; }
}
So it actually depends what environment you are programming in. If its a web browser, all of the code is in the global space actually and is run in order. so if you have <script src="file1"> then <script src="file2"> in your html file, and you put x = 10 in the first file and use it in the second, you will have no problems. If you are using node.js, I can post a solution for that as well, just let me know.
(btw if you put x = 10 in the second file and reference it from the first it will throw an error)
There are ways of avoiding this, such as using a document.ready function or wrapping things in functions and then calling them at the end. You need to make sure that functions and variables are created before being used (this is a common mistake beginners make and are confused by)

Cannot set property of undefined -- inserting text with javascript

I am currently trying to insert some text in a specific spot at a website, http://kawowii.com , however, I keep getting error messages. These error messages seem to originate from the section I am trying to select using javascript (variables txtClasses and styleClasses). The error messages are
Uncaught TypeError: Cannot set property 'textContent' of undefined
So, the variables seem to be undefined but I don't understand why. I have looked at the other answers and still cannot determine what is wrong.
Right now, I have
window.onload = function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
}
and I tried this
window.onload = function() {
var styleClasses = document.querySelectorAll(".coord-control leaflet-control");
function insertAfter1(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var brk = document.createElement("br");
insertAfter1(styleClasses[0], brk);
var div = document.createElement("div");
var textNode = document.createTextNode("Server: UP")
div.appendChild(textNode);
insertAfter1(brk, div);
}
My end goal is to change the website, kawowii.com , such that before Location :, it reads Server: UP using javascript.
I executed document.querySelectorAll("div.coord-control.leaflet-control"); on the website you provided, and it does in fact show an array with that element.
I think div.coord-control.leaflet-control is being inserted dynamically (perhaps after an AJAX request completes).
Therefore, you need to put your controlling logic inside the callback of the request:
whateverRequestIsInsertingThatElement.then(function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
});
I don't know if you're using promises or if the async method you're using provides a callback, but onload will happen in parallel with your async request, so you need to query for the dynamic element in the callback of the async request.
Not sure which API you're using to generate the map on your website, but usually any calls for location data will happen asynchronously (like the Google Maps API, for example). You can only manipulate dynamically generated DOM elements once the data has arrived.
Edit
You can see that the client is initially getting the configuration data from the route up/configuration. I would suggest looking for where that async call is being made in your source code, and then call querySelectorAll in its success handler.
I also see that in some of your sources, $.ajax is being called, so I assume somewhere in there, $.ajax is being called to the up/configuration route on your server.
So what I imagine happening is this:
You are querying your page for a your leaflet control but its returning an array of nothing. So when you try and access txtClasses[0] its undefined (since txtClasses.length == 0).
// this illustrates your problem
try {
// I am manually creating an empty array (your results)
var txtClasses = []
// this throws the error
txtClasses[0].bad = "throws an error";
} catch (e) {
// this just displays the error for you to see
document.getElementById("log").innerHTML += e.toString()
}
<div id="log"></div>
If you are expecting something back, you should check your selector is actually working (what I like to do is open up a web console and type my code right in there).
I noticed your selector changed in the first and second example too so make sure you read more about css selectors here.

Call to $.post() Jquery not passing parameters successfully

/**
* Created by quantumveil on 2/10/15.
*/
$(document).ready(function(){
$('a').on('click',function(){
//$href=$(this).attr('href');
//console.log($href);
var $convoid=$(this).attr('id');
console.log($convoid);
//$('#convoarea').load($href);
$.get('inbox.php',{convoid:$convoid},function(data){$('#convoarea').html(data);//the callback sets whati t had to
//now add the on click handler to send button
$('#send').on('click',function(){
var $msgbody=$('#sendbody').val();
console.log($msgbody);
///now what i have to do is sent this $msgbody to the inbox.php thru get k
$.post('inbox.php',{sendbody:$msgbody,convoid:$convoid},function(data){
$('#sendbody').before(data);
console.log('here'+$msgbody);
});//the callback function will append it to other messages :3
return false;
});
}//callback ends hre
);
return false;
});
//for send button
});
Hi. I'm trying to code a social networking site and I want the inbox to be responsive and dynamic. I've recently started learning Jquery for the purpose being. I've googled this before and found no help and so it brings me here on this community. The above Javascript/Jquery code is supposed to pass some post parameters when the SEND button is clicked. Another file, inbox.php, is to receive those and work appropriately. Now here's what bugs me. The callback function to $.post() is executed, so I'm assuming the parameters are being passed to inbox.php. But when I try accessing them in inbox.php using following line
if($msgbody=get_post('sendbody')&&$convoid=get_post('convoid'))
I only receive a value of 1 and not the message's actual body. Here's how the function get_post is defined
function get_post($var1){
if(isset($_POST[$var1])){$var=$_POST[$var1];
return filter($var);}
else return 0;
}
I've tried accessing them directly through $_POST['sendbody'] but an error of undefined index is being generated. Any help will be highly appreciated. (PS the other call to .get() in the beginning of this js file is passing the parameters so there's nothing wrong with file paths)
EDIT: It's fixed but I want an explanation. All I did was in the inbox.php changed the first line which was
if($msgbody=get_post('sendbody')
to
if(isset($_POST['sendbody'])$msgbody=$_POST['sendbody']
Now all I can wonder is if it has something to do with filter() function in the definition of my get_post() function. Anybody?

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources