calling a html function inside script in external js file - javascript

I have written a javascript function inside script tag of html file...
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll"></div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
<script type="text/javascript">
// set the focus to the input box
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
function verify(arguments){
}
</script>
</body>
</html>
i need to move the function verify(arguments) to an external js file.i have to move that because i am calling a nodejs child process which requires a module to be included.
How can i move the function to a external js file and subsequently call verify function from html file.

Make three files as such. It will solve your issue.
index.html
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
<!-- insert these two lines -->
<script type="text/javascript" src="verify.js" ></script>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll">
</div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
</body>
</html>
verify.js
function verify() {
}
other.js
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}

You can just copy paste the function to a .js file (ex:verifys.js) and include the .js file in the HTML using

Related

Show Captured WebCam file name to Next Page in Python (Flask)

I am trying to capture an image from WebCam and show its file name on the next page when the user clicks the Upload button.
Currently, the snap function is taking the image and working fine. But When the users click on the Upload button, nothing happened.
Expected Output: Click on the Upload button will open a New Page (Test2) and show the file name.
My Code
app.py
#app.route('/Test', methods=['GET','POST'])
def Test():
if request.method == 'POST':
return render_template('Test2.html',data=request.form['file'])
return render_template('Test.html')
if __name__ == '__main__':
app.run(debug=True)
Test.html
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.26/webcam.min.js" integrity="sha512-dQIiHSl2hr3NWKKLycPndtpbh5iaHLo6MwrXm7F0FM5e+kL2U16oE9uIwPHUl6fQBeCthiEuV/rzP3MiAB8Vfw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<form method="POST" enctype="multipart/form-data" id="myForm">
<table>
<tr>
<td>Name/EmailId</td>
<td>: <input type="text" name="userID"></td>
</tr>
<tr>
<td><input type="button" value="Upload" onclick="upload()"></td>
</tr>
</table>
</form>
<div id="my_camera"></div>
<input type="button" onclick="snap()" value="Snap">
<div id="results"></div>
</body>
<script>
function ShowCam() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach('#my_camera');
}
window.onload= ShowCam;
function snap() {
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="image" src="'+data_uri+'"/>';
} );
}
function upload() {
console.log("Uploading...")
var image = document.getElementById('image').src;
var form = document.getElementById('myForm');
var formData = new FormData(form);
formData.append("file", image);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test");
// check when state changes,
xmlhttp.onreadystatechange = function() {
}
xmlhttp.send(formData);
console.log(formData);
console.log(formData.get('file'));
console.log(formData.get('userID'));
}
</script>
Test2.html
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<p> {{data}}
</body>
</html>

Iframe runner with inputable URL

*Note I am using google app scripts
I am attempting to code a simple program as proof of concept, the concept being a Iframe that responds to the input of a html text box. So far I have looked into the triggers for the form element (I decided to use onsubmit) and researched the changing of an Iframe src. It starts out working, when I load it up it looks like this:
After that though, I type the url in the text box and click submit. It reloads, than displays a completely blank screen. Here is my code:
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Index.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include ('Css'); ?>
</head>
<body>
<form>
<input type="text" id="uri" name="uri"><br><br>
<input type="button" value="Submit" onclick="frameS">
<form>
<script>
function frameS() {
var urv = document.getElementById('uri');
var ura = urv.value;
url1 = trim(ura);
}
function trim(str){
return str.replace (/^\s+|\s+$/g, '');
}
</script>
<iframe allowfullscreen="true" width="600" height="400" id="abc" src="https://www.google.com/webhp?igu=1">sorry, couldn't load</iframe>
<?!= include ('javascript'); ?>
</body>
</html>
javascript.html
<script>
Logger.log('hit')
</script>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
Css.html *please note that the style sheet is not currently doing anything, I'm just including it for future development
<style>
/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
margin:0;
padding:0;
}
html, body {
margin: 0;
padding: 0;
}
body {
font-family: 'Roboto', sans-serif;
font-weight: 100;
}
fieldset {
border: 1px solid white;
color: white;
text-align: center;
width: 200px;
}
legend {
padding: 0 10px;
}
</style>
Thanks for your time and would appreciate any feedback on my code, related to the question or not.

How can I save the value of a custom field to wordpress' user_meta after altering it with javascript?

I'm using a plugin to create fields in user_meta inside WordPress database.
To create a page, first I created a Template. Then I asked for the fields' value with the plugin's function:
<?php $pc = rp_user_data_func("pc","1"); ?>
Then I used javascript to convert the PHP variable to javascript.
<script type="text/javascript"> var pc = <?php echo $pc; ?>;</script>
And finally used the variable pc in several javascript functions, which will change the value of the variable.
Now I need to update the custom field and save the new value in the WordPress' database, once the user clicks in a "save" button.
Is there is a specific way to do it in WordPress?
That's a simplified version of the code:
<?php
$pc = rp_user_data_func("pc","1");
if ( empty($pc) ) $pc = '0';
if (isset($_POST['submit']))
{
myfnc();
}
function myfnc()
{
$user_id = 1;
add_user_meta( $user_id , $pc , $pp , false );
}
?>
<html>
<head>
<script type="text/javascript">
var pc = <?php echo $pc; ?>;
function pc_add () {
pc = pc + 1;
alert(pc);
}
function pc_sub () {
pc = pc - 1;
alert(pc);
}
</script>
<style>
.square_add{
width: 100px;
height: 100px;
Background-color: green;
float: left;
}
.square_sub{
width: 100px;
height: 100px;
Background-color: red;
float: left;
}
</style>
</head>
<body>
<div class="square_add" onclick="pc_add();">ADD</div>
<div class="square_sub" onclick="pc_sub();">SUB</div>
<form action="." method="post">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Here is the page with this code working (changing the variable but not saving): http://www.anastorm.ihostfull.com/teste/
Just got help.
Here is the code working if anyone has the same problem:
<?php
$pc = rp_user_data_func("pc", "1");
if (empty($pc))
$pc = '0';
function myfnc($pc2) {
$user_id = 1;
update_user_meta($user_id, 'pc', $pc2);
$pct = rp_user_data_func("pc", "1");
unset($_POST);
}
if (isset($_POST['submit']) && !empty($_POST['pc'])) {
myfnc($_POST['pc']);
}
?>
<html>
<head>
<script type="text/javascript">
var pc = <?php echo $pc; ?>;
function pc_add() {
pc = pc + 1;
alert(pc);
document.getElementById('pc').setAttribute('value',pc);
}
function pc_sub() {
pc = pc - 1;
alert(pc);
document.getElementById('pc').setAttribute('value',pc);
}
</script>
<style>
.square_add{ width: 100px; height: 100px; Background-color: green; float: left;}
.square_sub{ width: 100px; height: 100px; Background-color: red; float: left;}
</style>
</head>
<body>
<div class="square_add" onclick="pc_add();">ADD</div>
<div class="square_sub" onclick="pc_sub();">SUB</div>
<form action="." method="post">
<input type="hidden" name="pc" id="pc" value="" />
<input type="submit" name="submit" value="submit">
</form>
</body>

Ajax form validation with php WITHOUT jQuery

I am learning JavaScript without jQuery.
Right now I am trying to pass some data from an input field to php and than pass a $variable from php to javascript. In jQuery this is easy with $.ajax.
But how do I do this with ONLY JavaScript? Here is my attempt. Right now I only want to pass the $_POST content from the inputfield. I didn't do any validation at this moment.
My plan is to make a validation with php and then pass an error message or more than one. Or in case of success an success message.
But out of my console log I am only getting NULL.
window.onload = function () {
var Input = document.querySelector('input#Input');
var InputButton = document.querySelector('button.formBtn');
InputButton.onclick = function () {
var InputRequest = new XMLHttpRequest();
InputRequest.open("POST", "ajax.php", true);
InputRequest.send();
InputRequest.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(InputRequest.response)
console.log(obj);
}
}
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Example</title>
<style>
#Input {
width: 200px;
height: 15px;
padding: 10px 0;
text-indent: 5px;
}
#Input:focus {
outline: none;
border: 1px solid lightblue;
}
</style>
</head>
<body>
<form name="form" action="ajax.php" method="post">
<input type="text" id="Input" name="inputTest">
<button type="submit" class="formBtn">Absenden</button>
</form>
<script src="ajax.js"></script>
</body>
</html>
<?php
$inputResponse = $_POST["inputTest"];
echo json_encode($inputResponse)
?>
You are missing a line and need to modify your send() line for sending POST content:
// You need to send the type
InputRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the post values in the send
InputRequest.send('key=value&key2=value2');
In the case of the send() you have to turn the keys and values to a query string. I think this is why so many use jQuery, it's done all this for you.

How to make my form post to its self

I have a form in which users can submit issues, what I want to happen is when users hit the add button, i want what they add to be posted in the box below. So say the add something, x out the window and come back to add something else later what they added previously will still be there.
here is my fiddle
http://jsfiddle.net/grahamwalsh/rCB9V/
IssueList(html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Issue List</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
</head>
<body>
<div class='issuelist'>
<form data-bind="submit:addIssue">
Add Issue: <input type="text" data-bind='value:issueToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: issueToAdd().length > 0">Add</button>
</form>
<p>Your Issues:</p>
<select multiple="multiple" data-bind="options:allIssues, selectedOptions:selectedIssues"> </select>
<div>
<button data-bind="click: removeSelected, enable: selectedIssues().length > 0">Remove</button>
<button data-bind="click: sortIssues, enable: allIssues().length > 1">Sort</button>
</div>
</div>
</body>
</html>
IssueList (js)
$(document).ready(function(){
var Issuelist = function () {
this.issueToAdd = ko.observable("");
this.allIssues = ko.observableArray(["test"]);
this.selectedIssues = ko.observableArray(["test"]);
this.addIssue = function () {
if ((this.issueToAdd() != "") && (this.allIssues.indexOf(this.issueToAdd()) < 0))
this.allIssues.push(this.issueToAdd());
this.issueToAdd("");
};
this.removeSelected = function () {
this.allIssues.removeAll(this.selectedIssues());
this.selectedIssues([]);
};
this.sortIssues = function () {
this.allIssues.sort();
};
};
ko.applyBindings(new Issuelist());
});
IssueListcss
body { font-family: arial; font-size: 14px; }
.issuelist { padding: 1em; background-color: #87CEEB; border: 1px solid #CCC; max-width: 655px; }
.issuelist input { font-family: Arial; }
.issuelist b { font-weight: bold; }
.issuelist p { margin-top: 0.9em; margin-bottom: 0.9em; }
.issuelist select[multiple] { width: 100%; height: 8em; }
.issuelist h2 { margin-top: 0.4em; }
You could have the form 'post' to its self then make an ajax request for their new issue and put it inside a div. I would also hold off on so much on the javascript or have support for those without it:
getissues.php
getissues.php
<?php
/*
connect to your database code
*/
$query = "select * from issues";
$result = mysql_query($query, $connect);
while($row = mysql_fetch_array($result))
{
echo $row['issues'];
echo '<hr>';
}
?>
process.php
process.php:
<?php
/*
connect to your database
*/
$issue = strip_tags$_POST['issue'];
$query = "insert into issues (issue) values ('$issue')";
$result = mysql_query($query, $connect);
?>
main form page:
<!DOCTYPE HTML>
<html>
<head>
<title>issue page</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
<script type="text/javascript">
function check()
{
var request = $.ajax({
url: "getissues.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#issues").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function validate()
{
var issue = $("#issue");
var errcount = 0;
if (issue == "")
{
errcount++;
alert("enter something");
}
if (errcount == 0)
{
/*
make request to php script to put issue into database
*/
$.post("process.php",
{
issue:issue
},
function(data,status){
window.alert("Request done!");
check();
});
}
}
</script>
</head>
<body>
<form action="issuelist.html" method="post">
Add Issue: <input type="text" name="issue"/>
Add Issue: <input type="text" name="issue" id="issue"/>
<button onclick="validate()">submit</button>
</form>
<div id="issues" class="issues">
<!--your ajax fetched issues will appear here-->
</div>
</body>
</html>
hope this helps!

Categories