How to get JS variable from Google Script? - javascript

Hello guys im new on Google Script,
im making an app that read the input from the box,
and then send it to the mysql.
I have this:
-
Codigo.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('getIp');
}
var connection = Jdbc.getConnection("jdbc:mysql://HOST:PORT/DB", "USER", "PW");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("Insert Into IPS Values(IPFromPrompt,0)");
Look at "IPFromPrompt" there is where i want IP from the following code
GetIp.html
<div>
<p>Click the button and enter your IP Addess.</p>
<button onclick="myFunction()">Try it</button>
<p id="AddIP"></p>
<script>
function myFunction() {
var IP = prompt("Please enter your IP Address", "");
if (person != null) {
document.getElementById("AddIP").innerHTML =
"Added " + IP + "to our database";
}
}
</script>
</div>
Do you know how can i do that?

I think you've got multiple problems here. You need a google.script.run call to trigger the .gs code from the HTML. Your myFunction() function needs to have google.script.run.
<script>
function myFunction() {
var IP = prompt("Please enter your IP Address", "");
var theUserInput = To Do . . .Get user input;
google.script.run
.withSuccessHandler(onSuccess)
.processInput(theUserInput)
}
function onSuccess(argIP) {
if (person != null) {
document.getElementById("AddIP").innerHTML =
"Added " + argIP + "to our database";
}
};
</script>
Codigo.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('getIp');
}
function processInput(argGetInput) {
var connection = Jdbc.getConnection("jdbc:mysql://HOST:PORT/DB", "USER", "PW");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("Insert Into IPS Values(IPFromPrompt,0)");
return result;
};

Related

display user name on the heading during onload

I'm making a dynamic website that need to show the user's name in the heading. The heading should say 'Hello, ', when the user enters their name into the text box and presses the button. And the name has to stay on the page even if I refresh the page.
What will be the javascript functions and html codes to implement this?
However, to implement this, the site need to read the query string when the page is loaded, not when the button is pressed. How can I write functions for the onload event for this?
I've tried this, but this doesn't work.
function setUserName() {
var userName = document.getElementById("userName").value;
localStorage.setItem("userName", userName);
}
function getUserName() {
var userName = localStorage.getItem("userName");
return userName;
}
function displayUserName() {
var userName = getUserName();
if (userName) {
document.write("Hello, " + userName);
} else {
document.write("Hello, world!");
}
}
<input type="text" id="userName">
<button onclick="setUserName()">Set Name</button>
<body onload="displayUserName()"></body>
Try this code, It might helpfull to you
function setUserName() {
var userName = document.getElementById("userName").value;
localStorage.setItem("userName", userName);
location.reload();
}
function getUserName() {
var userName = localStorage.getItem("userName");
return userName;
}
function displayUserName() {
var userName = getUserName();
if (userName) {
document.getElementById("helloText").textContent = "Hello, " + userName;
} else {
document.getElementById("helloText").textContent = "Hello, world";
}
}
<span id="helloText"></span>
<input type="text" id="userName" name="userName">
<button onclick="setUserName()">Set Name</button>
<body onload="displayUserName()">
</body>
Local storage wont work with the snippet by the way

Get async variable return empty

I am trying to create an add-in for the outlook windows application.
The following code should copy the email body to the clipboard, but it doesn't do that.
I need to press the run button two times in order to get the content copied, but I need to copy the content from the first time!
What is wrong with my code?
var messageBody = "";
export async function run() {
Office.context.mailbox.item.body.getAsync(
Office.CoercionType.Text,
function (asyncResult) {
if (asyncResult.status !== Office.AsyncResultStatus.Succeeded) {
messageBody = asyncResult.error;
} else {
messageBody = asyncResult.value;
}
});
copyToClipboard(messageBody)
}
function copyToClipboard(text) {
var copyhelper = document.createElement("input");
copyhelper.className = 'copyhelper'
document.body.appendChild(copyhelper);
copyhelper.value = text;
copyhelper.select();
document.execCommand("copy");
document.body.removeChild(copyhelper);
}

JavaScript $.GET not passing through

I am building a very simple chat application, nothing too fancy just a way for multiple users to chat at once.
The problem I am having is that whilst I can read and display messages from the database, no new messages will get inserted.
I am using JavaScript to pass a $.Get with the message and the username. I have checked the console and there is no errors showing but I have an undefined index: text and undefined index: username when I use POSTMAN to test.
Can anyone help push me in the right direction to solve this?
chat.php
<div class="wrapper">
<p id='chat-user'> </p>
<div id='chat-area'></div>
<form id='send-message-area'>
<textarea name="the-textarea" id="the-textarea" maxlength="150" placeholder="Start Typing..."autofocus></textarea>
</form>
<button id='chatSend' class="btn btn-info" type="submit">Post New Message</button>
<div id="the-count">
<span id="current">0</span>
<span id="maximum">/ 150</span>
</div>
</div>
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function () {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function () {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
function sendMessage() {
var chatInputString = $chatInput.val();
$.GET("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
process.php
<?php
error_reporting(E_ALL);
include ("connection.php");
$username = substr($_GET["username"], 0, 32);
$text = substr($_GET["text"], 0, 150);
$nameEscaped = htmlentities(mysqli_real_escape_string($conn, $username));
$textEscaped = htmlentities(mysqli_real_escape_string($conn, $text));
$timestamp = date("Y-m-d H:i:s");
$insertMessage = "INSERT INTO message (messageID, messageBody, timeSent, nickname, sent) VALUES ('', '$textEscaped', '$timestamp', '$nameEscaped')";
$result = mysqli_query($conn, $insertMessage);
Your postman request is wrong as shown in the picture
you are passing the param GET with the value send but in your php script you have $_GET["username"] and $_GET["text"] the method GET is already set in the left side of the url in the picture so you dont need to send it what you want to send is the param username and text so the url would look like this
http://xxxxxxx/testProcess.php?username=Guest&text=test
as for your javascript code the jquery method for get is $.get and not $.GET and you are missing a way to handle the submit of the form because your submit button is outside of the form so a correct way to this would be
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function() {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function() {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
//intercepting the submit event to call the sendMessage function
$("#send-message-area").on("submit", function(e) {
e.preventDefault();
sendMessage()
})
function sendMessage() {
var chatInputString = $chatInput.val();
$.get("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
})

Passing Javascript Input Values to a PHP file to Post to SQlite

I wanted to ask how can i get the values of the Javascript Input and store it into a php value so i can post this data into Sqlite3. Im receiving user inputs from the Javascript Prompts. Is there another way to accomplish this also. Any help would be greatly appreciated.
function myFunc(){
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
if(code==""||code==null||code!="1234"){
//Handle Error
window.location.href="error.html";
}
}
document.onreadystatechange = () => {
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
myFunc();
}
});
}
Using jquery you can use the $.post method:
function myFunc() {
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
var url = "phpToGetInputs.php";
var data = {
code: code,
email: email
}
$.post(url, data); // "send the data to the php file specified in url"
// code...
}
document.onreadystatechange = () => {
// code...
}
Then, in your PHP file (that you specified as the url)
phpToGetInputs.php:
<?php
if(isset($_POST['email'])) {
$email = $_POST['email']; // get the email input (posted in data variable)
$code = $_POST['code']; // get the code input (posted in data variable)
// do code that requires email and code inputs
}
?>
Use a jQuery post request to send the variable from javascript to php.
$.post([url], { "data" : text });
Look at this website for more information: https://api.jquery.com/jquery.post/

Unable to reload the same page after clicking submit button

I'm making a login page where if the email address already exists i want to stay on the same page and prompt the user that the email address already exists.
Here is the function which is the onClick function that will be called when the button is clicked
function login() {
var username = document.getElementById("username").value;
var pword = document.getElementById("pword").value;
var confpwd = document.getElementById("confpwd").value;
var email = document.getElementById("email").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var gender = document.getElementById("gender").value;
var t = 1;
if (t.toString() !== '0') {
var er = "Email-id already exists";
event.preventDefault();
document.getElementById("nemail").value = er;
document.getElementById("username").value = username;
document.getElementById("pword").value = "";
document.getElementById("confpwd").value = "";
document.getElementById("fname").value = fname;
document.getElementById("lname").value = lname;
document.getElementById("gender").value = gender;
}
}
You must pass a function to the <form onsubmit="return login()">. The login function must return true if you want to submit and false otherwise. See this answer for more details: JavaScript code to stop form submission
Working codepen to illustrate: http://codepen.io/DeividasK/pen/YZqwLO
Depending on how your code is setup to submit. You may just need to insert a return when the code realizes the email address is a duplicate. Something along this path might help prevent the page from moving forward.
if (ListOfExistingEmails.indexof(email) > 0 ) return false;

Categories

Resources