WebSockets can't establish connection to server - eclipse

I'm running the simple Echo example of WebSockets but it doesn't seem to establish a connection. This is happening on Windows 7, Eclipse, and Tomcat.
The error messages in firefox are:
"NetworkError: 404 Not Found - http://my_ip_address:8080/websockets/echo"
and
Firefox can't establish a connection to the server at ws://my_ip_address:8080/websockets/echo.
What am I missing? Is there some configuration I need to set up?
The jars I have in the build path are javax.annotation_1.0.jar and websocket-api-0.2.jar
The code I'm running:
package org.javaee.glassfishwebsocket;
import org.glassfish.websocket.api.annotations.WebSocket;
import org.glassfish.websocket.api.annotations.WebSocketMessage;
#WebSocket(path="/echo")
public class EchoBean {
#WebSocketMessage
public String echo(String message) {
System.out.println("##################### Message received");
return message + " (from your server)";
}
}
This is index.jsp:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<meta charset="utf-8">
<title>WebSocket Echo Client</title>
<script language="javascript" type="text/javascript">
console.log("trying to connect");
var wsUri = "ws://my_ip_address:8080/websockets/echo";
console.log("wsUri = ");
console.log(wsUri);
var websocket = new WebSocket(wsUri);
console.log("websocket = " );
console.log(websocket);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
function init() {
console.log("init called");
output = document.getElementById("output");
}
function send_echo() {
console.log("sending_echo with " + textID.value);
websocket.send(textID.value);
writeToScreen("SENT: " + textID.value);
}
function onOpen(evt) {
console.log("onOpen");
writeToScreen("CONNECTED");
}
function onMessage(evt) {
console.log("onMessage");
writeToScreen("RECEIVED: " + evt.data);
}
function onError(evt) {
console.log("onError");
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2 style="text-align: center;">WebSocket Echo Client</h2>
<div style="text-align: center;"><img style=" width: 64px; height: 64px;" alt=""src="HTML5_Logo_512.png"></div>
<br></br>
<div style="text-align: center;">
<form action="">
<input onclick="send_echo()" value="Press me" type="button">
<input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
</form>
</div>
<div id="output"></div>
</body>
</html>

Related

Sending a form via PHPMailer to an EMail adress - not working

I am trying to implement a form on my website - and make a PHPMailer send the content to my email address. I followed the directions from this website: https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
But its not working. I tried different email addresses, I tried tls and other ports and many more - nothing. Its alway the same: When I click the submit button, nothing happens. There's neither a success nor a failed echo.
I could really need some help!
This is the form code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style type="text/css">
input, textarea {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<input id="name" placeholder="Name" class="form-control">
<input id="email" placeholder="Email" class="form-control">
<input id="subject" placeholder="Subject" class="form-control">
<textarea class="form-control" id="body" placeholder="Email Body"></textarea>
<input type="button" onclick="sendEmail()" value="Send an Email" class="btn btn-primary"></type>
</div>
</div>
</div>
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() === "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
}
return true;
}
</script>
</body>
</html>
And this is the sendEmail.php:
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
//smtp settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "mymail#gmail.com";
$mail->Password = 'mypassword';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
//email settings
$mail->isHTML(true);
$mail->setFrom($email, $name);
$mail->addAddress("mymail#gmail.com");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
if ($mail->send()) {
$status = "success";
echo "Email is sent!";
} else {
$status = "failed";
echo "Something is wrong: <br><br>" . $mail->ErrorInfo;
}
?>
Thank you for your time and knowledge!
Andre
P.S.: #Merchizm: Thanks, I have changed the code, now it looks like this:
<?php
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;
if(isset.... and so on
Is this, what you mean?
I also added the jQuery to the head of the html file like this:
<script src="jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery30102019.js"></script>
But nevertheless, it is not working. Still the same issue.
Do you have another idea?
Thanks Andre
The JQuery library is not included in the html file, the request may not be going because of this.
Require files before using class.
require_once __DIR__. "/PHPMailer/src/PHPMailer.php";
require_once __DIR__."/PHPMailer/src/SMTP.php";
require_once __DIR__."/PHPMailer/src/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;
I think these will solve your problem.

Webapp button to duplicate sheet in google sheets

I'm trying to create a simple webapp button that it will duplicate sheet in Google sheets , I created the button in HTML and linked it to run the code when its clicked ! but it doesnt seem to work !, can someone tell me what I did wrong ?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id="btn">Create</button>
<script>
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
google.script.run.userClicked();
}
</script>
</body>
</html>
And here is the code for duplication :
function doGet() {
return HtmlService.createHtmlOutputFromFile('page');
}
function userClicked() {
SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();
var myValue = SpreadsheetApp.getActiveSheet().getRange("M1").getDisplayValue();
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("Daily Report " + myValue);
}
Duplicating & Deleting Sheets from a WebApp
Code.gs:
function dupSheet(dObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.setActiveSheet(ss.getSheetByName(dObj.name));
ss.duplicateActiveSheet();
var name="Daily Report " + sh.getRange("A1").getDisplayValue();
if(!sheetExists(name)) {
ss.renameActiveSheet("Daily Report " + sh.getRange("A1").getDisplayValue());
}
dObj['sA']=getSheetNames().sA;
return dObj;
}
function getSheetNames() {
var ss=SpreadsheetApp.getActive();
var shts=ss.getSheets();
var sObj={sA:[]};
shts.forEach(function(sh){
sObj.sA.push(sh.getName());
})
return sObj;
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('dup');
}
function delSheet(dObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(dObj.name);
ss.deleteSheet(sh);
dObj['sA']=getSheetNames().sA;
return dObj;
}
function sheetExists(name) {
var ss=SpreadsheetApp.getActive();
var sA=ss.getSheets();
for(var i=0;i<sA.length;i++) {
if(name==sA[i].getName()) {
return true
}
}
return false;
}
dup.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(sObj){
var select=document.getElementById('sel1');
sObj.sA.unshift('Please Select A File Name');
select.options.length=0;
for(var i=0;i<sObj.sA.length;i++) {
select.options[i]=new Option(sObj.sA[i],sObj.sA[i]);
}
})
.getSheetNames();
});
function dupSheet() {
$("#sel1").css('background-color','#ffff00');
google.script.run
.withSuccessHandler(function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select A File Name');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.dupSheet({name:$('#sel1').val()});
}
function delSheet() {
$("#sel1").css('background-color','#ffff00');
google.script.run
.withSuccessHandler(function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select A File Name');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.delSheet({name:$('#sel1').val()});
}
</script>
<style>
input{margin:2px 5px;}
</style>
</head>
<body>
<select id="sel1"></select><label for="sel1">Sheet Name</label>
<br /><input type="button" value="Duplicate Sheet" onClick="dupSheet();" />
<br /><input type="button" value="Delete Sheet" onClick="delSheet();" />
</body>
</html>
I used a little JQuery in there too.
As stated in the SpreadsheetApp reference.
getActiveSheet()
Gets the active sheet in a spreadsheet. The active sheet in a spreadsheet is the sheet that is being displayed in the spreadsheet UI.
Since you are not using any UI you should instead use other methods of accessing your Sheets and Spreadsheets, such as:
Obtaining your Spreadsheet
SpreadsheetApp.openById(id)
SpreadsheetApp.openByUrl(url)
Obtaining your Sheet(s)
Spreadsheet.getSheetByName(name)
Spreadsheet.getSheets()

Ionic app data from html to php server

I'm new to Ionic framework and am struggling to post data from HTML to PHP.
1.index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">HTML</h1>
</ion-header-bar>
<ion-view title="Signup">
<ion-nav-buttons side="left">
<button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-content class="has-header">
<div class="list list-inset">
<label class="item item-input">
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input">
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input">
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-positive button-dark" ng-click="signUp(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
</ion-pane>
</body>
</html>
app.js:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function () {
var request = $http({
method: "post",
url: "http://myurl.com/signup.php",
crossDomain : true,
data: {
email: $scope.email,
password: $scope.password,
username: $scope.username
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Successfully Created Account";
}
if(data == "2"){
$scope.responseMessage = "Create Account failed";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exist"
}
});
}
})
3.PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysql_connect("localhost","username",'password') or die ("Could not connect: " . mysql_error());;
mysql_select_db('dbname', $con);
$qry_em = 'select count(*) as cnt from users where email ="' . $email . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,pass,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
edit: I wrote a detailed post on how to post data from Ionic to PHP and you can view it here.
In the index.html file you have:
ng-click="signUp(userdata)
but then in the app.js file you have this:
$scope.signup = function () {
instead of something like:
$scope.signup = function (userdata) {
If you would go this route then your data should look like this:
data: {
email: userdata.email,
password: userdata.password,
username: userdata.username
}
However, you don't have to do it like this! You can do it like so that you remove the userdata from ng-click="signUp(userdata) and then in the app.js file in the data part you do it like this:
data: {
email: $scope.userdata.email,
password: $scope.userdata.password,
username: $scope.userdata.username
}

website on localhost not loading on refresh once the url is updated through window.pushState

My website is not loading on refreshing the page once the url is updated by window.pushState. My website is saved on this location: http://localhost/ajax.test/index.html
but after clicking the link with href="1" the url changes to http://localhost/ajax.test/1
.. here is the source code:
html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<ul>
<li class="list" id="1">home</li>
<li class="list" id="2">project</li>
<li class="list" id="3">about</li>
</ul>
<div id="dynamic"></div>
</body>
</html>
jQuery:
var url = 0;
var state=0;
$(document).ready(function(){
$('ul a').click(function(e) {
e.preventDefault();
alert(e.target);
url = $(this).attr("href");
history.pushState({page:url}, url,url);
loadContent(url);
});
});
$(window).bind('popstate', function(e){
state = event.state;
if(state){
loadContent(state.page);
}else{
loadContent("home");
}
});
function loadContent(currentPage){
alert(currentPage);
$.ajax({
type: "GET",
url: "ajax.php",
data: "id="+currentPage,
success: function(data){
$('#dynamic').html(data);
}
});
};
php:
<?php
$response = $_GET['id'];
if($response=="1")
{
echo "<h1>You loaded HOME</h1>";
}
else if($response=="2")
{
echo "<h1>You loaded PROJECT</h1>";
}
else if($response=="3")
{
echo "<h1>You loaded ABOUT</h1>";
}
?>

drop event is not fired

In the application below, the drop method is never called. The drop target (div2) is indicated by cancelling event in dragEnter and dragOver events but drop is not triggered. HTML and .dart are as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dandd</title>
<link rel="stylesheet" href="dandd.css">
</head>
<body>
<h1>Drag and drop</h1>
<p>Hello world from Dart!</p>
<div>
<label id='lbl' draggable='true' style='border: 1px solid; '>div1</label>
</div>
<p></p>
<div id='div2'>
<label>div2</label>
</div>
<script type="application/dart" src='dandd.dart > </script>
<script type='text/javascript'
src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
</body>
</html>
and here is dart file
import 'dart:html';
void main() {
query('#lbl')
..on.dragStart.add(onDragStart)
..on.dragEnd.add(onDragEnd);
query('#div2')
..on.dragEnter.add(onDragEnter)
..on.dragOver.add(onDragOver)
..on.drop.add(onDrop);
query('#div2')
..on.dragLeave.add(onDragLeave);
}
onDragStart(MouseEvent e) {
print('started');
var lbl = e.target as LabelElement;
lbl.style.opacity = '0.4';
e.dataTransfer.setData('text', lbl.id);
}
onDragEnd(MouseEvent e) {
var lbl = e.target as LabelElement;
lbl.style.opacity = '1.0';
print('drag end called');
}
onDragEnter(MouseEvent e) {
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
var x = e.target as DivElement;
x.classes.add('blueborder');
}
onDragOver(MouseEvent e) {
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
var x = e.target as DivElement;
x.classes.add('blueborder');
}
onDragLeave(MouseEvent e) {
var x = e.target as DivElement;
x.classes.remove('blueborder');
}
onDrop(MouseEvent e){
print('on drop called');
var x = e.target as DivElement;
x.classes.remove('blueborder');
String sid = e.dataTransfer.getData('text');
var v = query('#{sid}');
x.children.add(v);
}
It looks like a bug. See issue 6646.