I am able to capture a variable from the url of a published app script, but I am not sure how I can pass that variable to another function. The below script will not run the onRun function if a variable is included. My goal is to pass 2 variables, but one problem at a time.
function doGet(e) {
var id = e.parameter.id;
var minutes = e.parameter.min;
var html = '<p>'
+'<button onClick=google.script.run.onRun('+id+')>Run</button>' // Does not work when clicked
+'<button onClick=google.script.run.onRun()>Run without parameter</button>'
+'<button onClick=google.script.run.turnOn()>On</button>'
+'<button onClick=google.script.run.turnOff()>Off</button>'
+'</p>';
return HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function onRun(id){
Logger.log("id: "+id);
}
The trick is to use a public cache (Thank you Sandy Good).
function doGet(e) {
var id = e.parameter.id;
var minutes = e.parameter.min;
var cache = CacheService.getPublicCache();
cache.put("id", id, 30);
cache.put("minutes", minutes, 30);
var html = '<p>'
+'<button onClick=google.script.run.onRun()>Run without parameter</button>'
+'<button onClick=google.script.run.turnOn()>On</button>'
+'<button onClick=google.script.run.turnOff()>Off</button>'
+'</p>';
return HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function onRun(id){
var cache = CacheService.getPublicCache();
var id = cache.get('id'));
var minutes = cache.get('minutes'));
}
Either use a global variable, or put the values into cache.
To declare a global variable, declare the variable outside of a function:
var id = "";
var minutes = "";
function doGet(e) {
id = e.parameter.id;
minutes = e.parameter.min;
var html = . . . . . HTML HERE;
onRun(id, minutes);
return HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Or put the values into Cache:
function doGet(e) {
var id = e.parameter.id;
var minutes = e.parameter.min;
if (!!id) {cache.put('theid', id, 4000);};
if (!!minutes) {cache.put('min', minutes, 4000);};
var html = . . . . . HTML HERE;
onRun(id, minutes);
return HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Then you can retrieve the values from cache, or use the global variable anywhere in your code.
So, you don't need to pass anything from the HTML to the .gs code.
I don't see anything calling the onRun() function within the doGet() function.
You can call another function from the doGet() function, as long as it's before the return. return stops the function at that point.
function doGet(e) {
var id = e.parameter.id;
var minutes = e.parameter.min;
var html = . . . . . HTML HERE;
onRun(id, minutes);
return HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
You can't have:
return HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
onRun(id, minutes);
You can also trigger script to run from an HTML Script tag with window.onload = function() {code};:
<script>
window.onload = function() {
console.log("This onload did run");
code here;
};
</script>
To pass multiple variables, just separate them by a comma:
function doGet(e) {
code here;
onRun(id, minutes);
}
function onRun(argId, argMinutes) {
Logger.log('argId: ' + argId);
Logger.log('argMinutes: ' + argMinutes);
};
Related
After
$this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
is called script
jQuery(document).ready(function() {
var licznik = 0;
var aktywny = true;
window.onblur = function(){aktywny = false;};
window.onfocus = function(){aktywny = true; licznik = 0;};
var id = setInterval(function(){wyslijImpuls()},60000);
function wyslijImpuls() {
if(aktywny == false) {
licznik++; //żeby nie tracić czasu spędzonego na stronie (np: 30 sekund), gdy uzytkownik przelączy okno/zakładkę przeglądarki
}
if(licznik < 2) {
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
}
}
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
console.log(baseUrl);
});
and I revieved error
ReferenceError: baseUrl is not defined $.post(baseUrl+'Zapiszczas/',
{'ile': 1});
My question is how to pass baseUrl value to js? I'd like to mentioned that baseUrl is defined in config.ini and accessible in php Zend controller.
You have to save that baseURL in some input hidden or in a global var in javascript, when php send the rended page , javascript can't access to php variables, one is executed in server side and the other is exectued in the client side.
<script>
baseURL = this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
</scrip>
And then call in your next javascript script.
At the very Top of your ViewScript where you added $this->view->headScript()
//VIEW FILE
<?php
$this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
//TRY ADDING THIS:
$this->inlineScript()->captureStart();
echo "var baseURL = '" . $baseUrl . "';";
$this->inlineScript()->captureEnd();
//.... MORE CODES...
?>
<?php
// IN YOUR CONTROLLER: SINCE YOU HAVE ACCESS TO THE $baseUrl VARIABLE HERE
// TRY THIS IN THE APPROPRIATE ACTION:
public function showAction(){
//...HANDLE YOUR BUSINESS LOGIC
$arrViewModel = array();
$arrViewModel['baseUrl'] = $pointerToBaseURL;
$viewModel = new ViewModel($arrViewModel);
//IF $viewModel ALREADY EXIST BEFORE THIS POINT:
// YOU MAY JUST ADD THE baseUrl KEY LIKE SO
// $viewModel->setVariable('baseUrl', '$pointerToBaseURL');
return $viewModel;
}
?>
// IN YOUR JQUERY... $baseUrl SHOULD NOW BE AVAILABLE
// SINCE IT IS NOW GLOBALLY SCOPED FROM YOUR VIEW:
jQuery(document).ready(function() {
var licznik = 0;
var aktywny = true;
window.onblur = function(){aktywny = false;};
window.onfocus = function(){aktywny = true; licznik = 0;};
var id = setInterval(function(){wyslijImpuls()},60000);
function wyslijImpuls() {
if(aktywny == false) {
licznik++; //żeby nie tracić czasu spędzonego na stronie (np: 30 sekund), gdy uzytkownik przelączy okno/zakładkę przeglądarki
}
if(licznik < 2) {
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
}
}
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
console.log(baseUrl);
});
I hope this helps a bit...
Okay so I'm trying to set a JavaScript document to a variable in PHP?
Essentially I'm setting the WiFi speed I calculate in a Javascript document to a variable,so I can save the variable value in a database with other information as an instance.
The Javascript code is pretty long so I don't know if I should copy the whole code in and set it equal to the variable or if there's a syntax to set it to a variable.
I've seen:
<script type="text/javascript" src="file.js"></script>
Online for calling a Javascript file but not sure how to get that value and store it in a variable.
You could do something like this
$js = file_get_contents( 'http://www.example.com/javacsript.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $js));
echo $value;
Hope this will help you
The JavaScript must be executed in the browser client. The flow would be:
PHP generates HTML (wich includes the JS code)
HTML is sent to the browser
The browser renders the HTML and executes the JS
The browser communicates with the server to tell the result
Depending if the JS is a library or an script the precise steps would differ. But basically inside tags you will have to save the result to a variable and then make an AJAX call (easier with jQuery.ajax() ) to communicate that variable to the server and then the server can do something with it.
I hope that helps puting you on the right track. If you expand the info in your question, I will try to update my answer :)
You have to do this using a POST, possibly to the same PHP script.
<form method='post' id=myform>
<input type=hidden id=js-to-php value=0>
</form>
<script>
jQuery(document).ready(function(){
//calulcate the wifispeed using the long js code
//then save it in the field
$('#js-to-php').val(YOUR_SPEED);
// send the form
$('#myform').submit();
});
</script>
and then in the same script:
if( isset($_POST['js-to-wifi']) && $_POST['js-to-wifi']!='') {
// store your stuff in DB
}
So here is the Java script code:
//Source: http://stackoverflow.com/questions/5529718/how-to-detect-internet-speed-in-javascript
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg";
var downloadSize = 4995374; //bytes
window.onload = function() {
var oProgress = document.getElementById("progress");
oProgress.innerHTML = "Loading the image, please wait...";
window.setTimeout(MeasureConnectionSpeed, 1);
};
function MeasureConnectionSpeed() {
var oProgress = document.getElementById("progress");
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}
download.onerror = function (err, msg) {
oProgress.innerHTML = "Invalid image, or error downloading";
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;
function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
oProgress.innerHTML = "Your connection speed is: <br />" +
speedBps + " bps<br />" +
speedKbps + " kbps<br />" +
speedMbps + " Mbps<br />";
}
}
I want to get the value that this will return (I will edit the code so I am only getting one value) and then place it inside a php variable. The issue is when I run it on a webpage after using:
$Speed = file_get_contents( 'wiFiCalc.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $Speed));
echo $value;
I just get the code on the html page, as clami219 stated above. I just want to return that value to print it and store it in the database.
Also, Jobst, the way you wrote was kind of hard to follow. I am using a form action in my html code to go to the speed so it can be stored in the database before it returns to the next HTML page so could you explain how your code works?
I want to get data from javascript function (someone created this function before, and I need to get the data from this function):
Here are the javascript function:
function edit(a,b,c,d,e,f,g,h,i,j,k,l){
document.getElementById("frm").id.value=k;
document.getElementById("frm").name.value=a;
document.getElementById("frm").username.value=b;
document.getElementById("frm").emid.value=c;
document.getElementById("frm").dob.value=d;
setCheckedValue(document.forms['frm'].elements['gender'],e);
document.getElementById("frm").job.value=f;
document.getElementById("frm").info.value=g;
document.getElementById("frm").datejoin.value=h;
document.getElementById('locid').value=i;
document.getElementById('deptid').value=m;
var params = encodeURIComponent(document.getElementById("frm").username.value=b);
window.location.href="http://192.168.1.5/eleave/employee.php?lapplicant=" + params;
}
at PHP file I will use b.
This is the button who calls edit():
The code of that button are bellow:
<td align=\"center\">$uname</td><td align=\"center\">$loc1</td><td align=\"center\">$dept</td><td align=\"center\">$date</td><td align=\"center\"><button class=\"btn btn-mini\"data-toggle=\"modal\"href=\"#long\"
onClick=\"javascript:edit('$name','$uname','$emid','$dob','$gender','$job','$info','$datejoin','$locid','$deptid','$myid','$templatelist','newbal');\"><i class=\"icon-pencil\">
I've tried this javascript function in a new file:
function test_function() {
var width = 8;
var height = 9;
window.location.href="http://localhost/belajar/get_test.php?width=" + width + "&height=" + height;
}
and simply call in the PHP file such as:
<?php
$width = $_GET['width'];
$height = $_GET['height'];
print($width . " " . $height);
?>
I want to get b in edit() and use it in PHP file. I've tried to use the 2nd part in edit function. But, it doesn't work. Any idea?
This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/
I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}