Button won't execute Javascript no matter what I do - javascript

The following code below is supposed to work as follows, the user is suppose to input a URL, Proxy IP & Proxy port once they click "test" it would grab the response code and replace the html h5 "awaiting test" with the new status code text. I made another version of this same exact script and it worked via client but when you run via electron app and click test button all you get is an error how do I get the button "test" to execute the script? Any help would be greatly appreciated.
Index HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simple Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.3/semantic.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.3/semantic.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="header">Simple Tester v1.00</h1>
<div class="content">
<div class="proxytesturls">
<h3 id="url" style="color:#4a04de;" >Site URL:</h3>
<div class="ui large input">
<input type="text" placeholder="Google.com" id="siteurltext">
</div>
</div>
<div class="proxyip">
<h3 id="ip" style="color:#4a04de;">Proxy IP:</h3>
<div class="ui large input" id="proxyinput">
<input type="text" placeholder="1.1.1.1" id="proxyipinput">
</div>
</div>
<div class="proxyport">
<h3 id="port" style="color:#4a04de;">Proxy Port:</h3>
<div class="ui large input">
<input type="text" placeholder="8080" id="proxyportinput">
</div>
</div>
<input type="button" id="btnclick" value="test" onclick="pingProxy();">
<div class="ui raised segment" id="logger">
<h2 style="color:#4a04de;" id="logstext">Logger</h2>
<h5 id="awaitingtest">Awaiting test...</h5>
</div>
</div>
<script src="tester.js" type="text/javascript"></script>
</body>
</html>
tester.js
const request = require('request');
var pingProxy = require('ping-proxy');
var url = document.getElementById("siteurltext").value;
var proxyip = document.getElementById("proxyipinput").value;
var proxyport = document.getElementById("proxyportinput").value;
pingProxy({
proxyHost: proxyip,
proxyPort: proxyport,
proxyTestUrl: 'https://', url
},
function (err, options, statuscode) {
if (statuscode == 407) {
document.getElementById('awaitingtest').innerHTML = ('Status: Proxy Authentication Required');
}
if (statuscode == 200) {
document.getElementById('awaitingtest').innerHTML = ('Status: Valid Proxy!');
}
if (statuscode == 403) {
document.getElementById('awaitingtest').innerHTML = ('Status: Banned Proxy!');
}
if (statuscode == 401) {
document.getElementById('awaitingtest').innerHTML = ('Status: Unauthorized!');
}
}
);
Main.js
const electron = require('electron')
const {app, BrowserWindow} = require('electron')
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadFile('index.html')
}
app.on('ready', createWindow)
Errors:
Uncaught TypeError: callback is not a function
at pingProxyAsync (C:\Users***********\proxytester\node_modules\ping-proxy\ping-proxy.js:21)
at HTMLInputElement.onclick (index.html:37)

You may need to concatenate the proxyTestUrl. Replace the comma with a plus sign.
pingProxy({
proxyHost: proxyip,
proxyPort: proxyport,
proxyTestUrl: 'https://' + url
},

Related

Local undefined 404 when doing API call

This project is using the cocktail api to search for a specific ingredient (think gin or vodka) and then return all the drinks that contain the ingredient. I was able to get the results to display, but I wanted the thumbnail pic of the drink (included in the api as strDrinkThumb). When I try to get the pictures to display I get the follow error:
GET http://local/undefined 404 (Not Found)
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
let ingredients = document.getElementById('ingredients');
let searchTerm= document.getElementById('search-Bar');
let searchBtn = document.getElementById('searchBtn');
let drinkInfo = document.getElementById('drinkInfo');
let ingredientList = []
searchBtn.addEventListener("click", async (e) => {
const searchString = searchTerm.value.toLowerCase();
fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${searchString}`)
.then((response) => response.json())
.then((filteredIngredients) => {
displayIngredient(filteredIngredients.drinks);
})
.catch((error) => {
});
});
function displayIngredient(drinkData){
const ingredients = [];
//maps over array and makes new array
drinkInfo.innerHTML = drinkData.map( ({strDrink}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${drinkData.strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
drinkInfo.appendChild(drinkInfo);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cocktail App</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<input type="text" id="search-Bar" placeholder="Enter main ingredient..."/>
<button id="searchBtn">search</button>
</header>
<div class="drinkInfo" id="drinkInfo">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script type="text/javascript" src="./extrafile.js"></script>
</body>
</html>
In drinkData.map function you are only pulling strDrink value from the object, you need also get strDrinkThumb
Then you are trying get strDrinkThumb from drinkData which is an array, not an object.
Try this:
drinkInfo.innerHTML = drinkData.map( ({strDrink, strDrinkThumb}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');

How can I upload a file from my HTML form to my google drive? [duplicate]

This question already has an answer here:
How to upload a file via POST (doPost) to a Google Script's Web App?
(1 answer)
Closed 3 years ago.
I have an HTML form that lets the user upload a file. I want to then upload that file to my google drive.
My Javascript when the user clicks submit.
var data = new FormData();
data.append('resume', document.getElementById('file'));
fetch(scriptURL, {method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
My google script
doPost(e){
uploadFile(e.parameter['file])
}
function uploadFile(file, name){
var blob = file.myFile;
var name = "file";
var contentType = "application/pdf";
var fileBlob = Utilities.newBlob(blob, contentType, name);
var file = folder.createFile(fileBlob);
}
I want the uploaded pdf to be stored in my google drive but What my current code gives me is a 9 byte pdf file that just says undefined
Try this -
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Form').setTitle('Form')
}
function upload(obj) {
var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName)
DriveApp.createFile(blob);
return 'Done';
}
Form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<base target="_top">
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Montserrat', sans-serif;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
function uploadData() {
const f = document.getElementById('upFile');
[...f.files].forEach((file, i) => {
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
const obj = {
fileName: f.files[i].name,
mimeType: data[0].match(/:(\w.+);/)[1],
data: data[1]
};
var buttonID = document.getElementById('uploadButton');
$(buttonID).attr("disabled", "disabled");
google.script.run.withSuccessHandler((id) => {
M.toast({
html: id
});
$(buttonID).removeAttr("disabled");
}).upload(obj);
}
fr.readAsDataURL(file);
});
}
</script>
</head>
<body>
<div class="container center">
<div id="upload" class="col s12">
<form onsubmit="event.preventDefault(); uploadData()">
<div class="row">
<div class="input-field col s12 m6 l4 offset-m3 offset-l4">
<div>
<h4><br /></h4></div>
<div class="file-field input-field">
<div class="btn blue">
<span>File</span>
<input type="file" name="upFile" id="upFile" required="" aria-required="true">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload file" required="" aria-required="true">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 m6 l4 offset-m3 offset-l4">
<button class="waves-effect btn blue" type="submit" id="uploadButton">Upload</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
I took the liberty of adding some Materialize CSS - hope that's alright :)

unable to see the page. No error is being shown in console

I am trying to create a backbone application having login page and one dashboard page called home so for that I have created router having two routes.
After login, I am redirecting to the dashboard page
But I am not seeing anything at all when I run index file.
In the console also, no error is being shown.
var AppRoute = Backbone.Router.extend({
routes: {
"": "login", // #search/kiwis
"home": "home"
},
login: function(){
var loginTemplate = _.template($('#loginPage_template').html());
$('#htmlBodyContent').html(loginTemplate({}));
$('#somlogin').click(function(e) {
var loginData= {};
loginData.userName=document.getElementById('userName').value;
loginData.password=document.getElementById('password').value;
console.log(loginData);
if(loginData.userName==='admin' && loginData.password==='admin' ){
console.log("login successfull")
window.location.hash="#home";
}else{
console.log("do not match")
}
})
}
home: function() {
console.log("welcom to home")
}
});
var router = new Router();
Backbone.history.start();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="htmlBodyContent">
</div>
<script type="text/template" id="loginPage_template">
<div class="container">
<form class="login">
<h6>dawai<h6>
<input type="userName" class="form-control" id="userName" name="userName">
<input type="password" class="form-control" id="password" name="password">
<br>
<button type="button" class="btn-sm" id="loginBtn" >login</button>
</form>
</div>
</script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/underscore/underscore.js"></script>
<script src="bower_components/backbone/backbone.js"></script>
<script src="scripts/main.js"</script>
</body>
</html>
I see you use window.location to navigate your application, that is the problem. You need to use Backbone router api to navigate:
login: function() {
//...
this.navigate('home', {trigger: true});
//...
}

Attack all links with an ajax request

I've been trying create a pure function without jQuery or any other libraries to transform all links on my web app in an ajax request. But as you should know without success.
Can someone tell me where I'm going wrong?
function ajaxify() {
var content = document.getElementsByTagName('body');
var links = document.body.querySelectorAll('a');
[].forEach.call(links, function (link) {
console.log(link);
link.addEventListener('click', function (event) {
var url = link.href;
// Manipulate history
window.history.pushState({}, '', url);
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.status == 200) {
content[0].innerHTML = request.responseText;
} else {
alert('Request failed. Returned status of' + request.status);
}
};
request.send();
event.preventDefault();
});
});
}
Edit
One of pages that above script does not works
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="img/favicon.png" type="image/png">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="css/authentication.css" type="text/css">
<title>Web APP</title>
</head>
<body>
<div class="wrapper">
<div class="conteiner">
<i class="material-icons custom-arrow-back">arrow_back</i>
<img class="logomarca" src="img/logo.png">
<form name="form" id="form" action="ForgotPassword" method="POST">
<div class="align-form">
<div class="input-conteiner">
<input class="btn-material-style" type="email" id="email" name="email" maxlength="37" value="" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" autocomplete="off" required>
<label>Email</label>
<span class="bar"></span>
</div>
<p class="input-subscribe feedback"></p>
<div class="input-subscribe" style="margin-top: 2.4em">
<input class="btn-material-style" id="btn-submit-email" type="submit" name="submit" value="Request new password" style="border: 0">
</div>
</div>
</form>
</div>
</div>
<footer class="footer">
<p><span id="copyleft">©</span> 2016 - <span class="custom-color">Web APP</span></p>
</footer>
<script src="js/authentication.js"></script>
ajaxify();
</script>
</body>
Solved
The only problem is XMLHttpRequest does not let send script as DOM text for security reasons. So I gave up and now I'm using jQuery to do that. :(
querySelectorAll returns a NodeList, in order to add an event listening onto each HTMLElement within the NodeList you'll need to convert the NodeList to an array and loop through it:
var links= content[0].querySelectorAll('a');
[].forEach.call(links, function(link) {
link.addEventListener('click', function(event) { //code });
});
Also, have you tried this:
document.body.querySelectorAll('a');
querySelectorAll('a') will return an array of anchors. You need to iterate over that and then addEventListener to each one.

how to solve the error " Uncaught TypeError: Cannot call method 'changePage' of undefined"

I am just a beginner in phonegap as well as in javascript so while making a simple app for example, i wrote the following code in the index.html head and my main.js file is not getting included while i run the code. I hope anyone could help me out with the problem.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0rc2.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0rc2.js"></script>
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
</head>
<body onload="init()">
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Welcome to Phonegap</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<script>
$("#loginPage").live("pageinit", function(e) {
checkPreAuth();
});
</script>
</body>
</html>
here is the main.js file code as well.I just want only a particular login id to be valid.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
navigator.notification.alert("You entered a username and password");
handleLogin();
}
}
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var u = $("#username", form).val();
var p = $("#password", form).val();
var str1 = "burden123";
var str2 = "game1234";
var n1 = str1.localeCompare(u);
var n2 = str1.localeCompare(p);
if(u != '' && p!= '') {
$.post("http://www.coldfusionjedi.com/demos/2011/nov/10/service.cfc? method=login&returnformat=json", {username:u,password:p}, function(res) {
if(n1==0 && n2==0) {
$.mobile.changePage("some.html");
} else {
navigator.notification.alert("Your login failed", function() {});
}
$("#submitButton").removeAttr("disabled");
},"json");
} else {
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
this line in your code should be changed to
<script type="text/javascript" charset="utf-8" src="main.js"></script>
as main js is in same folder of index.html page.
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
in above check you path in src also try putting it above and place a alert at top in main.js
check if all scripts above this is including or not.
Thanks

Categories