imgur upload script error - imgur

Hi Your post does not have much context to explain the code sections, please explain your scenario Clearly more. I took the tedious hours, a warning to ask a question
I get the following error
I'd appreciate if you help
thanks
imgur.php image upload script
<?php
$current_api_key = "api key";
?>
<html>
<body>
<style type="text/css">
body { font-family: Verdana, Geneva, sans-serif; font-size:12px; color:#000; background:#f9f9f9; margin:0px; padding:0px; }
a { color:#21759b }
a:hover { color:#d54e21; }
h1 { font-size: 18px; font-weight: bold; }
h2 { font-size: 14px; font-weight: bold; }
#media-upload-header ul { margin-left:21px; margin-top:11px; margin-bottom:8px; padding:0px; }
#media-upload-header li { display:inline; margin-right:8px; }
#media-upload-header a { text-decoration:none; }
#content { background:#FFF; border-top:#dfdfdf solid 1px; border-bottom:#dfdfdf solid 1px; padding:25px; }
.current { color:#d54e21; background-color:#FFF; padding:5px 10px 10px 10px; border-top:#dfdfdf solid 1px; border-left:#dfdfdf solid 1px; border-right:#dfdfdf solid 1px; }
</style>
<div id="content" align="center">
<h1>Choose image to upload :</h1>
<form enctype="multipart/form-data" action="<?php echo $plugin_path; ?>api.php?api=<?php echo $current_api_key; ?>" method="POST">
<input name="userfile" type="file" /><br /><br />
<input type="submit" value="Upload to imgur.com" />
</form>
</div>
</body>
</html>
api.php other script
<html>
<head>
<style>
body { font-family: Verdana, Geneva, sans-serif; background-color: #FFF; }
h1 { font-size: 14px; font-weight: bold; color: #000; }
a { color:#000; }
#insert_box_img { float:left; width:200px; }
#insert_box_button { float:left; width:400px; }
</style>
</head>
<body>
<?
$api_key = "api key";
$file = getcwd() . '/' . basename( $_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $file);
list($width, $height, $file_type) = getimagesize($file);
if ($file_type == 3) {
$image = imagecreatefrompng($file);
imagealphablending($image, false);
imagesavealpha($image, true);
ob_start();
imagepng($image);
$data = ob_get_contents();
ob_end_clean();
}
if ($file_type == 2) {
$image = imagecreatefromjpeg($file);
imagealphablending($image, false);
imagesavealpha($image, true);
ob_start();
imagejpeg($image);
$data = ob_get_contents();
ob_end_clean();
}
if ($file_type == 1) {
$image = imagecreatefromgif($file);
imagealphablending($image, false);
imagesavealpha($image, true);
ob_start();
imagegif($image);
$data = ob_get_contents();
ob_end_clean();
}
$pvars = array('image' => base64_encode($data), 'key' => $api_key);
$timeout = 30;
$curl = curl_init();
$post = http_build_query($pvars);
curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$xml_raw = curl_exec($curl);
curl_close ($curl);
unlink($file);
$xml = new SimpleXMLElement($xml_raw);
if ($xml->error_code != '') {
$imgur_error_code = $xml->error_code;
$imgur_error_msg = $xml->error_msg;
settype($imgur_error_code, "string");
settype($imgur_error_msg, "string");
echo "<h1>Error #" . $imgur_error_code . ", " . $imgur_error_msg . "</h1>";
}
else {
imagedestroy($image);
$imgur_original = $xml->original_image;
$imgur_large_tbn = $xml->large_thumbnail;
$imgur_small_tbn = $xml->small_thumbnail;
$imgur_image_hash = $xml->image_hash;
$imgur_delete_hash = $xml->delete_hash;
$imgur_page = $xml->imgur_page;
$img_delete_page = $xml->delete_page;
settype($imgur_original, "string");
settype($imgur_large_tbn, "string");
settype($imgur_small_tbn, "string");
?>
<script language="javascript">
function insert_original()
{
var postCode = '<img src="<?php echo $imgur_original; ?>">';
top.send_to_editor(postCode);
return;
}
function insert_large_tbn()
{
var postCode = '<img src="<?php echo $imgur_large_tbn; ?>">';
top.send_to_editor(postCode);
return;
}
function insert_small_tbn()
{
var postCode = '<img src="<?php echo $imgur_small_tbn; ?>">';
top.send_to_editor(postCode);
return;
}
</script>
<div align="center">
<div id="insert_box_img">
<h1>Small thumbnail :</h1>
<img src="<?php echo $imgur_small_tbn ?>" border="0" />
<h1>Large thumbnail :</h1>
<img src="<?php echo $imgur_large_tbn ?>" border="0" />
</div>
<div id="insert_box_button">
<h1>One-click insert into post...</h1>
<input name="insert1" type="button" onclick="insert_original()" value="Original image" />
<br/><br/>
<input name="insert2" type="button" onclick="insert_large_tbn()" value="Large thumbnail w/ link to original" />
<br/><br/>
<input name="insert3" type="button" onclick="insert_small_tbn()" value="Small thumbnail w/ link to original" />
</div>
<div style="clear:both;"></div>
</div>
<?php
}
?>
</body>
</html>
show this error
Error #1003, Image format not supported, or image is corrupt.

api.php is using an outdated version of Imgur's API URL. The line which reads
curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
should be changed to
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/1/upload.xml');

Related

GET request works on local machine but doesn't work on Linux server

For the Discord bot, I need to send a GET request to a specific service to shorten a specific link.
I am using the https module from NPM to send a GET request, namely:
var https= require('https');
let opts = {
host: 'clicksfly.com',
path: '/api?api=SECRETCODEd&format=text&url=www.google.com',
method: 'GET'
};
const req = https.request(opts, res => {
res.on('data', d => {
console.log(d.toString());
});
});
req.end();
This code works completely on my computer, and it returns a shortcut link. However, on the server where my bot is located, this code does not work, namely, it sends a long code of an incomprehensible HTML page:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA
-Compatible" content="IE=Edge,chrome=1" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Just a moment...</title>
<style type="text/css">
html, body {width: 100%; height: 100%; margin: 0; padding: 0;}
body {background-color: #ffffff; color: #000000; font-family:-apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, "Helvetica Neue",Arial, sans-serif; font-size: 16px; line-height: 1.7em;-webkit-font-smoothing: antialiased;}
h1 { text-align: center; font-weight:700; margin: 16px 0; font-size: 32px; color:#000000; line-height: 1.25;}
p {font-size: 20px; font-weight: 400; margin: 8px 0;}
p, .attribution, {text-align: center;}
#spinner {margin: 0 auto 30px auto; display: block;}
.attribution {margin-top: 32px;}
#keyframes fader { 0% {opacity: 0.2;} 50% {opacity: 1.0;} 100% {opacity: 0.2;} }
#-webkit-keyframes fader { 0% {opacity: 0.2;} 50% {opacity: 1.0;} 100% {opacity: 0.2;} }
#cf-bubbles > .bubbles { animation: fader 1.6s infinite;}
#cf-bubbles > .bubbles:nth-child(2) { animation-delay: .2s;}
#cf-bubbles > .bubbles:nth-child(3) { animation-delay: .4s;}
.bubbles { background-color: #f58220; width:20px; height: 20px; margin:2px; border-radius:100%; display:inline-block; }
a { co
lor: #2c7cb0; text-decoration: none; -moz-transition: color 0.15s ease; -o-transition: color 0.15s ease; -webkit-transition: color 0.15s ease; transition: color 0.15s ease; }
a:hover{color: #f4a15d}
.attribution{font-size: 16px; line-height: 1.5;}
.ray_id{display: block; margin-top: 8px;}
#cf-wrapper #challenge-form { padding-top:25px; padding-bottom:25px; }
#cf-hcaptcha-container { text-align:center;}
#cf-hcaptcha-container iframe { display: inline-block;}
</style>
<meta http-equiv="refresh" content="35">
<script type="text/javascript">
//<![CDATA[
(function(){
window._cf_chl_opt={
cvId: "2",
cType: "non-interactive",
cNounce: "24390",
cRay: "6c53b849cf342c52",
cHash: "d48c5950487c1fc",
cPMDTk: "TGRJIKcYNeQaUi4qjEFvtSSBAfHY03rt_7_2xESZg24-1640788159-0-gaNycGzNBuU",
cFPWv: "g",
cTTimeMs: "1000",
cRq: {
ru: "aHR0cHM6Ly9jbGlja3NmbHkuY29tL2FwaT9hcGk9Yjg4YjhjZDg5MjBmNzZjYTBhMDcwYmM1ZDQ2MmI5MWQ4NmNmMGI1ZCZmb3JtYXQ9dGV4dCZ1cmw9d3d3Lmdvb2dsZS5jb20=",
ra: "",
rm: "R0VU",
d: "47w2TkCdqOr0Tck9v6/aqzyT2lSjPuS81Akssy/HzRxaWwidLLHW74f1FOQUFn/lAWOf/De/txE6ePHyUXrUmXM3ltJ8BE5ZvBPCPF8n2muZ2XR33mqdLzTVcErGWEq0YeyjdXkgvNvZTVfkM70rOAHAYJb2suMmaUae91VBgKpIVnkw26Wwr7P9mFqluxpQREHJ+QAxC4CpNsMdQOYJD7GNYns
Pr+wFSJihZBiPymo8rx4Uegxcnf9sJhvItS7WDNrr5Eja/zEf4hnTasqLHeOknNIJ9np06y0fspnkEF6/qDgp4NSQdLEYV5pkbwXCqbEOfuBX3fGRuX0+qajK1exUUGPxLrzqL37mdD/fNA0wYhiDSZS2BHHlyler2S88M7vXBvLBNM78BQmVEan/CTnzck3sGqUgs40Ckhy4HEncspT7Lu87RPsqQ8kf/qiC8IDxLRDOGnJF5AThherCErcAv7zUi6gVr5bB5/qEW74Rp8c1Q1vwAImtYNC0SxPJ5LbgnUdOUeUhHUe0s5Rw4Dx7zIbHA9VpMpyAhemSaHA=",
t: "MTY0MDc4ODE1OS4wMTEwMDA=",
m: "f24BKfHcLktTTQE1Q1/kNNARn0oM+B4CwSSsUmvRs6g=",
i1: "+c9VZZ25U4G4BasL/L05rg==",
i2: "Kz28rQ4qA6UO6XV/AQmYsA==",
zh: "va4hCvZPZYx/dl/GK/fh92PoHUPArv8s552Q7x2/qYo=",
uh: "DV4j3Tmrbi5Rs1q3ahwVS6SgbPbI7np5884QO1u1Cgg=",
hh: "pl7IslarvVZvfg0YHKRLaukHlDa0TtpfuYJctN/tpqM=",
}
}
window._cf_chl_enter = function(){window._cf_chl_opt.p=1};
})();
//]]>
</script>
</head>
<body>
<table width="100%" height="100%" cellpadding="20">
<tr>
<td align="center" valign="middle">
<div class="cf-browser-verification cf-im-under-attack">
<noscript>
<h1 data-translate="turn_on_js" style="color:#bd2426;">Please turn JavaScript on and reload the page.</h1>
</noscript>
<div id="cf-content" style="display:none">
<div id="cf-bubbles">
<div class="bubbles"></div>
<div class="bubbles"></div>
<div class="bubbles"></div>
</div>
<h1><span dat
a-translate="checking_browser">Checking your browser before accessing</span> clicksfly.com.</h1>
<div id="no-cookie-warning" class="cookie-warning" data-translate="turn_on_cookies" style="display:none">
<p data-translate="turn_on_cookies" style="color:#bd2426;">Please enable Cookies and reload the page.</p>
</div>
<p data-translate="process_is_automatic">This process is automatic. Your browser will redirect to your requested content shortly.</p>
<p data-translate="allow_5_secs" id="cf-spinner-allow-5-secs" >Please allow up to 5 seconds…</p>
<p data-translate="redirecting" id="cf-spinner-redirecting" style="display:none">Redirecting…</p>
</div>
<form class="challenge-form" id="challenge-form" action="/api?api=b88b8cd8920f76ca0a070bc5d462b91d86cf0b5d&format=text&url=www.google.com&__cf_chl_f_tk=TGRJIKcYNeQaUi4qjEFvtSSBAfHY03rt_7_2xESZg24-1640788159-0-gaNycGzNBuU" method="POST" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="md" value="xkEcrpi8t1.QjXZlqCsIjpdEGmDY_IdcgbTeOQYnWyM-1640788159-0-AVJqqT9Tvcgthj9NRbMs79IOh1RWvyCKlp7aD5F_0fTulpLPDbF-RLTYMcO9QsWjbBGbgh_Wc6nalQ5OfQ5AfETkxDG89DCtXBs8eS12TTViPp2xtMEUwLQfccIK6xA-lcZ4eYMUD7iGkWMVnLq0WPsKybj52VXST_RhKTB-_CYc8HLABUkmygvc7bzMkoratKKK7jNCM_kV2ROIF-sxykIOseW9Qzg7-8xGIN55DCtQdF-AGg6P5EZPgZ--6fgAXmpDOt6HdnUfRXOy
sjKKD1m0LEswX3mcqY2AQnh1ocfg4rXbBy7FwTX2SHRb0qWbQ96DC5Jw6uq4NuqzYdbTiRNx_jq2Kujxhu5F74LpJQfxBR13hujaoqODdBxhbl3m-X9EzNNloGdNgK5ahkTD9BtUPMaYL_bsygKJXLtlkq7sUsGB3OxPsKFFb87UfgaSWXTc0HrXoRXoa1f91kRM02RyBnbOzu6eV4BA0-hfaW0n3oO7LkKoSbXuibYYst4Y1I21_-BxrFE5r23okOcM698KGlACH9TzAbBmEx0H_k1P1J99RPV4od1oBfQrDCbfE6Hwehaj77g63-NwfMUtweEEG_Iegj-7gJIsmTdpGqENcIgZzBkVWJoQyJtmkvkQSRqBGrauqvLZuUpT4J2JcwRwPs-ybpK7WKKzRyOA2vK2UrrjRpQrhIhqj7ay7Cz1eWiyJXnwPvzu3wRfE5t3CHMU0od5eKuEdh0Ruq1y6Tj7n22ho9sn92vPwWkVdk9CeT101bJ83LRrJk3XPvIOi1E" />
<input type="hidden" name="r" value="EfcTylAJ6D0BDns4eSFtNCPUpLdh4A7kjPglrCzMQeo-1640788159-0-AanhkUrahNV4ONtYb+sTo+uauUtmeERPrcNryzlJIFlv4alUyU7Lhm1SHiFYP9lTDLGxy6PM9+uYgtQ3AXWBqoUr39qaO6Kto/d9EArJN8X52JJkzrLUVcoj//vu++QxzuTIsT0NhOLdCTIYZzGxDsCSzhYEIQ8iGpN8u+eBdcBgQkvZUNlETgynelJUNpjv5x3CX9nfBo0C/WlEjYWhC++TP68liuZatG0bIA2uxXOfopNCMch5xtiulF9GYMafWhIwxVM1+LHYAscRN+PUhZluA1+6tpkLyMneVRry2+3LA0I3zRET0Vq/5Z+MYRrwLU7XdpAWqDyFQPN/YsG4V5qWdwX2NKsLRzP6dxwbvrX14NFpP6Xrsj8Dr9PAs1zPce2gETT3Wv5LpDeUbX9k/Tlf1IkLhLse2Kx0giwa9dI5vEZb1SavlGYkGKUXPJmc80gocm+WvZVUcNiXbkLnlXixbbCcKQzLMK1e9rZIrLJv7kuzlIar/hd9A7otR5+I5iUIUnnnyWLJjuYcnN3+c9W9r0clCPtT+GpMAPkjz5boWU1PgJbUEH8JpFicCDy9cJcui+VXNe1b6GQgSwPZl0ABjzTqfWxVWjgxYnA1Jz+euFT2BSlEIvGg2Mhj4bJNa2RcbwmnBT3stMObWg3JS9IivnBZmkUsprWiPr07qr/FAWSRpjYpykmCp7CEgssEKbGwk7fUc43RlJclVKyW8R00JN7BpQH/44TwKPrKN9G
i4XW39lPLJP0SjoVu73QAqssV/D2bHtEJ2DDJ5mmt62lp8ukiMw9XBqmm6slygREwvx8gmaAm1vt3FV7TXD5goI17r1yPWGqww0s46+py2bhaWq4fcVmzZ6nDoTdPmF49A47zBcOXCRPKRiX33eL+nYZnQ1LH7IFfgqtu8YWaDjkVGzCyTHnGVOYTr2XVhNAAjLmi/nW4kJgVzrufS+Is26NxpbjMXWtBjkFTrYE+r+E7tqhSOmlLPIQxVpX0dfoXd3XOiBTV2GO5pGgHJCEVcDGufUQvguiogLwkV1zBlu29lfsrSjfhKvJjH28nFL3v+HPBhXOrPelN2xtrSlHXmoRtTCA9e075lZUOFMBpjBPGCw2uZD2i/pHVtFwa+0p63AgqnGF/IrDnVuaFs165kMpGnHumggU5ZK5XqAIYwKmr106mK6QjmOx5WDd6oc0WsRYVfpVwQB4P+8jWf9VAl6PfFBhQKzqwj5G0mQDcrhUfx8rknzjr78Nh6Bv51ZXUtNL1y76XMwhsN+6Cu2T1Ms1r+eSdRgo6LpueBF0pr6mA/xUIQXgP4P6j0C9dRPH/MhsdJmKiDv925ju7+xcFRsDILdZ7vsae69tDN04q0d4sBzKvOmMsIxWiikr9P4D7XvB5RTnwGQ9a7XILf0q8jZmEtLeMV9qfY3AzYFvvi/m3zGMZmNbFNkyg1PvJfIRGch7vUfFXqT5YYgJZ7M9gBN4yLxC+WtP1UKmoOHd+cQg9xzeTNxuvQDM/yjMynW0uxZlxtdL4Ucp4PtHhKWvjNg7LIJB6niNAqeDMsBLov6F1P+QLs4GVdS1fRtpgnmxHN/+y3/V6g/9/Eb/trYmWC+3e2pD1DIAYw7BUjhyo+KRPjDKXUR2CqC0nQjp8Q7uOOfT+JK9uuONsiXfcE0SucL4K6r1UvDmT/qXxPNwtt5hIzTmbuaJ63HV+Urh49m07"/>
<input type="hidden" value="133b40e5940ea08e8901277e08bc72e4" id="jschl-vc" name="jschl_vc"/>
<!-- <input type="hidden" value="" id="jschl-vc" name="jschl_vc"/> -->
<input type="hidden" name="pass" value="1640788160.011-Z8znjbzNhw"/>
<input type="hidden" id="jschl-answer" name="jschl_answer"/>
</form>
<script type="text/javascript">
//<![CDATA[
(function(){
var a = document.getElementById('cf-content');
a.style.display = 'block';
var isIE = /(MSIE|Trident\/|Edge\/)/i.test(window.navigator.userAgent);
var trkjs = isIE ? new Image() : document.createElement('img');
trkjs.setAttribute("src", "/cdn-cgi/images/trace/jschal/js/transparent.gif?ray=6c53b849cf342c52");
trkjs.id = "trk_jschal_js";
trkjs.setAttribute("alt", "");
document.body.appendChild(trkjs);
var cpo=document.createElement('script');
cpo.type='text/javascript';
cpo.src="/cdn-cgi/challenge-platform/h/g/orchestrate/jsch/v1?ray=6c53b849cf342c52";
if (window._cf_chl_opt.cPMDTk && window.history && window.history.replaceState && window.URLSearchParams) {
var ogU = location.pathname + location.search + location.hash;
var p = new URLSearchParams(location.search);
p.set('__cf_chl_rt_tk', window._cf_chl_opt.cPMDTk);
history.replaceState(null, null, location.pathname + '?' + p.toString() + location.hash);
cpo.onload = function() {
history.replaceState(null, null, ogU);
};
}
document.getElementsByTagName('head')[0].appendChild(cpo);
}());
//]]>
</script>
<div id="trk_jschal_nojs" style=
"background-image:url('/cdn-cgi/images/trace/jschal/nojs/transparent.gif?ray=6c53b849cf342c52')"> </div>
</div>
<div style="display: none;">table</div>
<div class="attribution">
DDoS protection by <a rel="noopener noreferrer" href="https://www.cloudflare.com/5xx-error-landing/" target="_blank">Cloudflare</a>
<br />
<span class="ray_id">Ray ID: <code>6c53b849cf342c52</code></span>
</div>
</td>
</tr>
</table>
</body>
</html>
I tried to use CURL instead of modules, however the same problem occurred with it, but that did not lead me to a possible solution, and also tried to use other modules to send the request, however with them the same problem.
Also, I found out that this HTML code is associated specifically with the site of the link shortening service, but, as you understand, I want to refer to the service API.

How add, delete, edit and save functions will work on multiple tables in HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap Table with Add and Delete Row Feature</title>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
body {
color: #404e67;
background: #f5f7fa;
font-family: "Open Sans", sans-serif;
}
.table-wrapper {
width: 700px;
margin: 30px auto;
background: #fff;
padding: 20px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
.table-title {
padding-bottom: 10px;
margin: 0 0 10px;
}
.table-title h2 {
margin: 6px 0 0;
font-size: 22px;
}
.table-title .add-new {
float: right;
height: 30px;
font-weight: bold;
font-size: 12px;
text-shadow: none;
min-width: 100px;
border-radius: 50px;
line-height: 13px;
}
.table-title .add-new i {
margin-right: 4px;
}
table.table {
table-layout: fixed;
}
table.table tr th,
table.table tr td {
border-color: #e9e9e9;
}
table.table th i {
font-size: 13px;
margin: 0 5px;
cursor: pointer;
}
table.table th:last-child {
width: 100px;
}
table.table td a {
cursor: pointer;
display: inline-block;
margin: 0 5px;
min-width: 24px;
}
table.table td a.add {
color: #27c46b;
}
table.table td a.edit {
color: #ffc107;
}
table.table td a.delete {
color: #e34724;
}
table.table td i {
font-size: 19px;
}
table.table td a.add i {
font-size: 24px;
margin-right: -1px;
position: relative;
top: 3px;
}
table.table .form-control {
height: 32px;
line-height: 32px;
box-shadow: none;
border-radius: 2px;
}
table.table .form-control.error {
border-color: #f50000;
}
table.table td .add {
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
var index = $("table tbody tr:last-child").index();
var row =
"<tr>" +
'<td><input type="text" class="form-control" name="current shift" id="cur_shft"></td>' +
'<td><input type="text" class="form-control" name="name current" id="n_curr"></td>' +
'<td><input type="text" class="form-control" name="shift handedover" id="shft_hndover"></td>' +
'<td><input type="text" class="form-control" name="name next" id="n_next"></td>' +
'<td><input type="text" class="form-control" name="time" id="shft_time"></td>' +
"<td>" +
actions +
"</td>" +
"</tr>";
$("table").append(row);
$("table tbody tr")
.eq(index + 1)
.find(".add, .edit")
.toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this)
.parents("tr")
.find("td:not(:last-child)")
.each(function () {
$(this).html(
'<input type="text" class="form-control" value="' +
$(this).text() +
'">'
);
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
</script>
</head>
<body>
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-8">
<h2><b>Shift Information</b></h2>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-info add-new">
<i class="fa fa-plus"></i> Add New
</button>
</div>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>Current Shift</th>
<th>Associates in Current Shift</th>
<th>Shift Handedover to</th>
<th>Associates in Next shift</th>
<th>Shift Handover time</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
<td>Chandu</td>
<td>Second</td>
<td>Venkata</td>
<td>15:30</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"
><i class="material-icons"></i></a
>
<a class="edit" title="Edit" data-toggle="tooltip"
><i class="material-icons"></i></a
>
<a class="delete" title="Delete" data-toggle="tooltip"
><i class="material-icons"></i></a
>
</td>
</tr>
<tr>
<td>Second</td>
<td>Venkata</td>
<td>Third</td>
<td>Mallikharjuna</td>
<td>23:00</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"
><i class="material-icons"></i></a
>
<a class="edit" title="Edit" data-toggle="tooltip"
><i class="material-icons"></i></a
>
<a class="delete" title="Delete" data-toggle="tooltip"
><i class="material-icons"></i></a
>
</td>
</tr>
<tr>
<td>Third</td>
<td>Mallikharjuna</td>
<td>First</td>
<td>Saikiran</td>
<td>06:30</td>
<td>
<a class="add" title="Add" data-toggle="tooltip"
><i class="material-icons"></i></a
>
<a class="edit" title="Edit" data-toggle="tooltip"
><i class="material-icons"></i></a
>
<a class="delete" title="Delete" data-toggle="tooltip"
><i class="material-icons"></i></a
>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
I have created 6 html tables. I have written JS script for add, delete, edit and save functions. Now if i click on the add button for one table, the row is getting added 6 times to all tables. Please help on how to resolve this. Above example code is one such table and I just cloned the table to 5 other html files. I just changed the row column names

Keep Added Image Behind Image while Moving

I'm using fabricjs 1.7.22 with a toggle-able background and the ability to add images behind said background images. I have it nearly working as I'd like but my problem is that when I move an image uploaded from my computer behind a frame image, it isn't staying behind the frame in the first canvas. However, it is working as it should in the static canvases. What am I doing wrong?
I have canvas.preserveObjectStacking = true; set, so am confused.
Please see my code snippet below, choose an image, and upload an image from your computer to see replicate my problem.
var canvas = [],
image;
canvas.push(new fabric.Canvas('c0'));
for (i = 1; i <= 7; i++) {
canvas.push(new fabric.StaticCanvas('sc' + i));
}
canvas.preserveObjectStacking = true;
function dropText() {
var text = new fabric.IText('Type here...', {
fontSize: 27,
top: 10,
left: 10,
});
canvas[0].add(text);
}
canvas[0].on('object:added', onModified);
canvas[0].on('object:modified', onModified);
canvas[0].on('object:scaling', onModified);
canvas[0].on('object:moving', onModified);
function onModified(option) {
var ob = option.target;
var index = canvas[0].getObjects().indexOf(ob);
ob.clone(function(obj) {
for (i = 1; i <= 7; i++) {
canvas[i].insertAt(obj, index, true);
}
});
};
// New Photo to Canvas
document.getElementById('addimg').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
var image = new fabric.Image(imgObj);
image.set({
left: 10,
top: 10,
}).scaleToHeight(100);
canvas[0].add(image);
canvas[0].sendToBack(image);
updateCanvas();
};
};
reader.readAsDataURL(e.target.files[0]);
};
$('#update').click(function() {
updateCanvas();
});
function updateCanvas() {
var json = JSON.stringify(canvas[0]);
for (i = 1; i <= 7; i++) {
canvas[i].loadFromJSON(json);
}
}
// Toggling Images
function replaceImage(imgUrl) {
if (!isImageLoaded) return; //return if initial image not loaded
image.setSrc(imgUrl, function() {
canvas[0].renderAll();
updateCanvas();
});
}
// Default (Blank)
fabric.Image.fromURL('https://i.imgur.com/SamdNdX.png', function(img) {
isImageLoaded = true;
image = img.set({
selectable: false,
evented: false,
}).scale(0.5);
canvas[0].add(image);
canvas[0].sendToBack(image);
updateCanvas();
});
$('#save').click(function() {
html2canvas($('#imagesave'), {
onrendered: function(canvas) {
var a = document.createElement('a');
// toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
a.download = 'myfile.jpg';
a.click();
}
});
});
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #f00;
margin: 0px;
display: block;
}
td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
vertical-align: baseline;
}
#addimg {
position: relative;
overflow: hidden;
cursor: pointer;
}
input {
position: absolute;
font-size: 50px;
opacity: 0;
right: 0;
top: 0;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<button onclick="dropText();" class="dropdown-item">Add Text</button>
<a id="addimg" class="dropdown-item">
<input type="file" name="file" />Add Image</a>
<button id="save">Save</button>
<button onclick="replaceImage('https://i.imgur.com/SamdNdX.png')">Blank</button>
<button onclick="replaceImage('https://i.imgur.com/RuZ5HTH.png')">Image A Pic</button>
<button onclick="replaceImage('https://i.imgur.com/u3Knj4R.png')">Image B Pic</button>
<div id="imagesave">
<table>
<tr>
<td>
<canvas id="c0" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc1" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc2" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc3" width="187.5" height="318.75"></canvas>
</td>
</tr>
<tr>
<td>
<canvas id="sc4" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc5" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc6" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc7" width="187.5" height="318.75"></canvas>
</td>
</tr>
</table>
</div>
You need to add preserveObjectStacking:true to each canvas, as you are implementing the preserveObjectStacking:true to the array and not to the canvas.
var canvas = [],
image;
canvas.push(new fabric.Canvas('c0',{preserveObjectStacking:true}));
for (i = 1; i <= 7; i++) {
canvas.push(new fabric.StaticCanvas('sc' + i,{preserveObjectStacking:true}));
}
canvas.preserveObjectStacking = true;
function dropText() {
var text = new fabric.IText('Type here...', {
fontSize: 27,
top: 10,
left: 10,
});
canvas[0].add(text);
}
canvas[0].on('object:added', onModified);
canvas[0].on('object:modified', onModified);
canvas[0].on('object:scaling', onModified);
canvas[0].on('object:moving', onModified);
function onModified(option) {
var ob = option.target;
var index = canvas[0].getObjects().indexOf(ob);
ob.clone(function(obj) {
for (i = 1; i <= 7; i++) {
canvas[i].insertAt(obj, index, true);
}
});
};
// New Photo to Canvas
document.getElementById('addimg').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
var image = new fabric.Image(imgObj);
image.set({
left: 10,
top: 10,
}).scaleToHeight(100);
canvas[0].add(image);
canvas[0].sendToBack(image);
updateCanvas();
};
};
reader.readAsDataURL(e.target.files[0]);
};
$('#update').click(function() {
updateCanvas();
});
function updateCanvas() {
var json = JSON.stringify(canvas[0]);
for (i = 1; i <= 7; i++) {
canvas[i].loadFromJSON(json);
}
}
// Toggling Images
function replaceImage(imgUrl) {
if (!isImageLoaded) return; //return if initial image not loaded
image.setSrc(imgUrl, function() {
canvas[0].renderAll();
updateCanvas();
});
}
// Default (Blank)
fabric.Image.fromURL('https://i.imgur.com/SamdNdX.png', function(img) {
isImageLoaded = true;
image = img.set({
selectable: false,
evented: false,
}).scale(0.5);
canvas[0].add(image);
canvas[0].sendToBack(image);
updateCanvas();
});
$('#save').click(function() {
html2canvas($('#imagesave'), {
onrendered: function(canvas) {
var a = document.createElement('a');
// toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
a.download = 'myfile.jpg';
a.click();
}
});
});
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #f00;
margin: 0px;
display: block;
}
td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
vertical-align: baseline;
}
#addimg {
position: relative;
overflow: hidden;
cursor: pointer;
}
input {
position: absolute;
font-size: 50px;
opacity: 0;
right: 0;
top: 0;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<button onclick="dropText();" class="dropdown-item">Add Text</button>
<a id="addimg" class="dropdown-item">
<input type="file" name="file" />Add Image</a>
<button id="save">Save</button>
<button onclick="replaceImage('https://i.imgur.com/SamdNdX.png')">Blank</button>
<button onclick="replaceImage('https://i.imgur.com/RuZ5HTH.png')">Image A Pic</button>
<button onclick="replaceImage('https://i.imgur.com/u3Knj4R.png')">Image B Pic</button>
<div id="imagesave">
<table>
<tr>
<td>
<canvas id="c0" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc1" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc2" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc3" width="187.5" height="318.75"></canvas>
</td>
</tr>
<tr>
<td>
<canvas id="sc4" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc5" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc6" width="187.5" height="318.75"></canvas>
</td>
<td>
<canvas id="sc7" width="187.5" height="318.75"></canvas>
</td>
</tr>
</table>
</div>

node.js + socket.io + recursively adding replies

I've cobbled together a web page to control an Onkyo receiver via its serial port using parts of several diverse examples I found mostly on stackexchange. It works well, but I've run into the problem highlighted by #user568109 in the first link below where I think I have "initialized connection eventlisteners from within your routes" instead of globally. (Each time the web page is refreshed, the number of replies sent increments by one.) The problem is I can't see how to do initialize it globally. I tried removing the function:
io.sockets.on('connection', function (socket) {......}
but leaving the ....... part, as was done successfully in the second link below, but that didn't work for my case. Is there a simple fix? I'm a complete novice to node and javascript so I'm hoping it is obvious to someone.
Apart from the additional replies each time the web page is refreshed, it works well. (Apart from initializing the on off switch, the radio buttons and volume slider get initialed correctly, but I'll try to address that once I've sorted this sockets thing out).
Thanks!
Socket.io emits duplicate data after browser refresh
node.js + socket.io - duplicate websocket writes?
Here's the code snippet:
var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);
var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyUSB0", {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1
}
);
server.listen(8080);
app.use(express.static('public'));
io.sockets.on('connection', function (socket) {
socket.on('toOnkyo', function (data) {
paramVal = data.value;
var buf = new Buffer(16);
buf.write(paramVal, "utf-8");
serialPort.write(buf);
io.sockets.emit('toOnkyo', {value: paramVal});
});
serialPort.on('data', function(data) {
io.sockets.emit('onkyoReply', {value: data.toString().substr(0,7)});
});
});
console.log("running");
body {
text-align: center;
margin-top: 50px;
background: #50D0A0;
}
input[type=range]{
-webkit-appearance: none;
width: 80%;
}
input[type=range]::-webkit-slider-runnable-track {
height: 10px;
background: #ddd;
border: none;
border-radius: 3px;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 32px;
width: 32px;
border-radius: 50%;
background: goldenrod;
margin-top: -12px;
}
input[type=range]:focus {
outline: none;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #ccc;
}
.radioLeft
{
text-align:left;
}
.onoffswitch {
position: relative; width: 90px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
display: block; width: 200%; margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
box-sizing: border-box;
}
.onoffswitch-inner:before {
content: "ON";
padding-left: 10px;
background-color: #34A7C1; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}
.onoffswitch-switch {
display: block; width: 18px; margin: 6px;
background: #FFFFFF;
position: absolute; top: 0; bottom: 0;
right: 56px;
border: 2px solid #999999; border-radius: 20px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Onkyo Controller</title>
<meta name="viewport" content="width=400px" />
<script src="socket.io/socket.io.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
Sent: <span id="sliderVolText"></span><br>
Reply: <span id="replyTextHex"></span>
(Decimal: <span id="replyText10"></span>)<br>
Mode: <span id="modeText"></span><br>
PowerText: <span id="powerText"></span><br>
Power: <span id="power"></span><br>
onoffText: <span id="onoffText"></span><br>
onoff: <span id="onoff"></span>
<script>
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
</script>
<form class="onoffswitch" >
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="showOnoff(checked)">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</form>
<form name="modeForm" method="get" action="" onsubmit="return false;">
<p> <label for="mode0"><input type="radio" value="0x00" name="modeForm" id="mode0" onclick="showMode(this.value)"> Stereo</label>
<label for="mode1"><input type="radio" value="0x01" name="modeForm" id="mode1" onclick="showMode(this.value)"> Direct</label>
<label for="mode2"><input type="radio" value="0x0C" name="modeForm" id="mode2" onclick="showMode(this.value)"> All Ch stereo</label>
<label for="mode3"><input type="radio" value="0x42" name="modeForm" id="mode3" onclick="showMode(this.value)"> THX Cinema</label>
<label for="mode4"><input type="radio" value="0x84" name="modeForm" id="mode4" onclick="showMode(this.value)"> PLllx THX Cinema</label>
<label for="mode5"><input type="radio" value="0x11" name="modeForm" id="mode5" onclick="showMode(this.value)"> Pure</label>
</form>
<form name="slideForm" method="get" action="" onsubmit="return false;">
<input type="range" id= "inputSlider" min="0" max="100" value="vol" step="1" oninput="showVolume(this.value)" />
</form>
<br><br>
<div class="results"></div>
<script type="text/javascript">
var socket = io.connect();
var ctrlType = "";
socket.on('toOnkyo', function (data) {
ctrlType = data.value.toString().substr(2,3);
if (ctrlType == "MVL" && !(data.value.toString().substr(5,4)=="QSTN")){
document.getElementById("inputSlider").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("sliderVolText").innerHTML = data.value;
}
if (ctrlType == "LMD" && !(data.value.toString().substr(5,4)=="QSTN")){
document.getElementById("mode").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("modeText").innerHTML = data.value;
}
if (ctrlType == "PWR" && !(data.value.toString().substr(5,4)=="QSTN") ){
document.getElementById("power").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("powerText").innerHTML = data.value;
}
if (ctrlType == "PWR" && !(data.value.toString().substr(5,4)=="QSTN") ){
document.getElementById("onoff").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("onoffText").innerHTML = data.value;
}
});
socket.on('onkyoReply', function (data) {
var done = false;
ctrlType = data.value.toString().substr(2,3);
document.getElementById("replyTextHex").innerHTML = data.value;
document.getElementById("replyText10").innerHTML = parseInt(data.value.toString().substr(5,2),16);
if (ctrlType == "LMD"){
setCheckedValue(document.forms['modeForm'].elements['modeForm'],"0x"+data.value.toString().substr(5,2));
}
if (ctrlType == "PWR"){
var val = parseInt(data.value.toString().substr(5,2),16);
setCheckedValue(document.forms['powerForm'].elements['powerForm'],"0x"+data.value.toString().substr(5,2));
}
if (ctrlType == "MVL" && done == false){
document.getElementById("inputSlider").value = parseInt(data.value.toString().substr(5,2),16);
document.querySelector('.results').innerHTML = parseInt(data.value.toString().substr(5,2),16);
done = true;
}
});
function showVolume(newValue) {
document.getElementById("sliderVolText").innerHTML="\!1MVL"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1MVL"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
}
function showMode(newValue) {
document.getElementById("modeText").innerHTML="\!1LMD"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1LMD"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
}
function showOnoff(newValue) {
document.getElementById("onoffText").innerHTML="\!1PWR"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1PWR"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
}
socket.emit('toOnkyo', { value: "\!1PWRQSTN"+"\r\n" });
socket.emit('toOnkyo', { value: "\!1LMDQSTN"+"\r\n" });
socket.emit('toOnkyo', { value: "\!1MVLQSTN"+"\r\n" });
</script>
</body>
</html>
Found a solution based on Ian Wooten's blog:
http://www.ianwootten.co.uk/2011/07/04/maintaining-references-to-sockets-with-express-and-socket-io/
Great!
server.listen(8080);
app.use(express.static('public'));
var paramVal = 0;
var countRep = 0;
var countSend = 0;
var buf = new Buffer(16);
var global_socket;
io.sockets.on('connection', function (socket) {
global_socket = socket;
global_socket.on('toOnkyo', function (data) {
paramVal = data.value;
buf.write(paramVal, "utf-8");
serialPort.write(buf);
console.log(paramVal.toString().substr(0,7) + " (" + parseInt(paramVal.toString().substr(5,2),16) + ")\r\n");
global_socket.emit('toOnkyo', {value: paramVal});
console.log('new'+paramVal);
countSend=countSend+1;
console.log('count send '+ countSend);
});
});
serialPort.on('data', function(data) {
console.log('data received: ' + data.toString().substr(0,7) + " (" + parseInt(data.toString().substr(5,2),16) + ")");
global_socket.emit('onkyoReply', {value: data.toString().substr(0,7)});
countRep=countRep+1;
console.log('count '+ countRep);
});
console.log("running");

socket.io doesn't work in webkit mobile with node.js

i'm using this node.js code:
var server = require("socket.io").listen(6666);
server.sockets.on("connection", function(message)
{
message.on("newMessage", function(data)
{
server.sockets.emit("sendEvent", data);
});
});
and this html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Online chat</title>
<style>
body
{
color: #333;
background: #333;
font-family: "Helvetica", Arial;
font-size: 14px;
text-align: center;
}
.container
{
background: #ccc;
border-radius: 1em;
box-shadow: 0px 5px 5px rgba(0,0,0,0.5);
text-shadow: 5px 5px 5px rgba(0,0,0,0.5);
margin: 1em auto;
padding: 1em;
width: 90%;
}
input
{
display: block;
font-size: 12px;
margin: 1em auto;
padding: 0.5em;
width: 95%;
}
span
{
display: block;
font-size: 12px;
margin: 1em auto;
padding: 0.5em;
width: 95%;
text-align: left;
}
</style>
<script src="/resources/js/socket.io.js"></script>
<script type="text/javascript">
<!--
var websocket = io.connect("http://localhost:6666");
window.onload = function()
{
websocket.on("sendEvent", function(data)
{
var chat = document.getElementById('zchat');
var span = document.createElement('span');
var txt = document.createTextNode(data);
span.appendChild(txt);
if(chat.hasChildNodes())
chat.insertBefore(span, chat.firstChild);
else
chat.appendChild(span);
});
var form = document.getElementById('zform');
var message = document.getElementById('zmessage');
form.onsubmit = function(e)
{
websocket.emit("newMessage", message.value);
return false;
};
};
//-->
</script>
</head>
<body>
<div class="container">
<form id="zform">
<label>Message: </label>
<input type="text" name="zmessage" id="zmessage" placeholder="Please insert message" required />
<input type="submit" />
</form>
</div>
<div id="zchat" class="container">
</div>
</body>
</html>
works fine with normal browsers but with i probe with samsung's bada's "dolfin" browser based on webkit and it doesn't work, can someone probe it with another mobile browser? thanks :)
server.js
//...
var server = require("socket.io").listen(6969);
//...
index.html
//...
var websocket = io.connect("http://192.168.100.103:6969");
//...
i think the SATAN's port is evil for this, jajajaja and NEVER use localhost, always the PC's public IP

Resources