I am trying to put different data from cgi output in different DIV
Did that with below code, but now when new data comes, it appends the DIV,
I want to replace the DIV data and not append it.
I am new to this, As I am a hardware engg. do not know much of coding.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h1>Console</h1>
<pre>
<div id="d1" style="width: 25%; height: 200px; ">
</div>
<div id="d2" style="width: 25%; height: 200px; ">
</div>
</pre>
<script>
var source = new EventSource('/cgi-bin/data.cgi');
source.onmessage = function(e) {
var o = document.getElementById("d1");
o.innerHTML += e.data1 + '<br>';
var x = document.getElementById("d2");
x.innerHTML += e.data2 + '<br>';
};
</script>
</body>
</html>
Just want to replace existing data in D1 with new data which is coming from CGI.
You just need to do the following.
o.innerHTML = e.data1 + '<br>';
just remove that "+" before "="
When I put any keyword in search area it will display, but in my php, I always display. I want change the Query in API for any keywords I want and search.
<html>
<head>
<title>Google Search API</title>
</head>
<body>
<div id="content">
<input type="text" id="Query">
<button id="add">Search</button>
</div>
<script>
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.htmlTitle should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + "<b>" + item.title + "</b>" + "<br>" + item.snippet + "<br>" + "<a href='" + item.link + "'>" + item.displayLink + "</a>";
}
}
</script>
<script id="searchme"></script>
<script type="text/javascript">
var search_query = 'https://www.googleapis.com/customsearch/v1?q=Query&cx=004123968310343535430%3Aaxml6iel9yo&key=AIzaSyDxPcphnrcN9_dfkRkFTbwkv44m1-HI1Hg&callback=hndlr';
document.getElementById('searchme').src = search_query;
</script>
</body>
</html>
I have a macro to open IE, login into a page, and pull a table. This is for our router, not a website. It's giving me the error "Object variable or With block variable not set." It highlights the "username" line in yellow in debugger.
This is the section of code from the website:
<form name="login_form" method="post" style="display:none">
<input type="hidden" name="mode" value="submit" />
<input type="hidden" name="option" value="login" />
<div id="login_box">
<div id="company_name">Copyright © <span id="company_name_text"></span>. All rights reserved.</div>
<div id="login_box_layout">
<strong>Login</strong><br><br>
Username:<br>
<input type="text" class="text_box" name="username" tabindex="1" autocapitalize="off"><br><br>
Password:<br>
<input type="password" class="text_box" name="password" tabindex="2" autocomplete="off"><br><br>
<input type="button" value="Login" tabindex="3" class="submit_action">
<div class="smart_status" id="smart_status"></div>
</div>
</div>
</form>
And this is the macro:
Sub GetTable()
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate "http://192.168.1.1"
Do While ie.Busy: DoEvents: Loop
Do Until .ReadyState = 4
DoEvents
Loop
.Document.all.Item("username").Value = "admin123"
.Document.all.Item("password").Value = "password123"
.Document.forms(0).submit
End With
'now that we’re in, go to the page we want
ieApp.Navigate "http://192.168.1.1/cgi-bin/MANGA/index.cgi?mode=config&option=utlog"
Do While ieApp.Busy: DoEvents: Loop
Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
'get the table based on the table’s id
Set ieDoc = ieApp.Document
Set ieTable = ieDoc.all.Item("device_log")
'copy the tables html to the clipboard and paste to teh sheet
If Not ieTable Is Nothing Then
Set clip = New DataObject
clip.SetText "" & ieTable.outerHTML & ""
clip.PutInClipboard
Sheet1.Select
Sheet1.Range("A1").Select
Sheet1.PasteSpecial "Unicode Text"
End If
End Sub
Here is the complete page source:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="apple-itunes-app" content="app-id=582215646, affiliate-data=, app-argument=">
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<link rel="shortcut icon" href="connicon.cgi?type=favicon">
<title>Web Admin | Welcome</title>
<style>
body {
font-family:Arial, Helvetica, sans-serif;
}
#warning {
margin:110px auto 10px;
padding:30px;
width:300px;
background:#FCC;
color:red;
font-size:12px;
}
#login_box {
position:relative;
margin:80px auto 0;
width:834px;
height:434px;
background:url("connicon.cgi?type=login_screen") no-repeat;
}
#login_box_layout {
position:relative;
margin:0 auto 0;
padding:140px 0 0;
width:250px;
}
.text_box {
width:200px;
}
.smart_status {
border:1px solid #FFCC56;
color:#157015;
font-weight:700;
background:#FFFFB0;
padding:5px 3px 3px 6px;
margin:10px auto 0;
}
#company_name {
position:absolute;
top:385px;
left:22px;
border-radius:0 0 3px 3px;
padding:5px;
width:780px;
background:#E9F1FC;
font-size:9px;
}
div.notif_box {
position:absolute;
top:22px;
left:22px;
border-radius:8px 8px 0 0;
padding:10px;
height:85px;
width:770px;
background: black;
color:red;
font:700 24px Arial, Helvetica, sans-serif;
text-align:center;
}
</style>
<!-- jQuery UI - Style Sheet -->
<link rel="stylesheet" href="../../jquery-ui.css?$Name: Release-8_4_119_PATCH1 $" type="text/css" />
<!--
<link rel="stylesheet" href="../../jquery-ui-custom.css?$Name: Release-8_4_119_PATCH1 $" type="text/css" />
-->
<script src="../../MANGA/jquery.js?$Name: Release-8_4_119_PATCH1 $" type="text/javascript"></script>
<!-- jQuery UI - Core -->
<script type="text/javascript" src="../../MANGA/jquery.ui.core.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script type="text/javascript" src="../../MANGA/jquery.ui.widget.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script type="text/javascript" src="../../MANGA/jquery.ui.button.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script type="text/javascript" src="../../MANGA/jquery.ui.mouse.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script type="text/javascript" src="../../MANGA/jquery.ui.position.js?$Name: Release-8_4_119_PATCH1 $"></script>
<!-- jQuery UI - Dialog -->
<script type="text/javascript" src="../../MANGA/jquery.ui.draggable.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script type="text/javascript" src="../../MANGA/jquery.ui.resizable.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script type="text/javascript" src="../../MANGA/jquery.ui.dialog.js?$Name: Release-8_4_119_PATCH1 $"></script>
<script src="../../MANGA/global.js?$Name: Release-8_4_119_PATCH1 $" type="text/javascript"></script>
<script src="../../MANGA/validate_scripts.js?$Name: Release-8_4_119_PATCH1 $" type="text/javascript"></script>
<script type="text/javascript" src="../../MANGA/menulib.js?$Name: Release-8_4_119_PATCH1 $"></script>
</head>
<body>
<noscript>
<div id="warning">You must enable Javascript to access the Web Admin.</div>
</noscript>
<form name="login_form" method="post" style="display:none">
<input type="hidden" name="mode" value="submit" />
<input type="hidden" name="option" value="login" />
<div id="login_box">
<div id="company_name">Copyright © <span id="company_name_text"></span>. All rights reserved.</div>
<div id="login_box_layout">
<strong>Login</strong><br><br>
Username:<br>
<input type="text" class="text_box" name="username" tabindex="1" autocapitalize="off"><br><br>
Password:<br>
<input type="password" class="text_box" name="password" tabindex="2" autocomplete="off"><br><br>
<input type="button" value="Login" tabindex="3" class="submit_action">
<div class="smart_status" id="smart_status"></div>
</div>
</div>
</form>
</body>
</html>
<script>
var r0t1e=function(s){return s.toLowerCase().replace(/[a-z]/g,function(c){var v="m";return String.fromCharCode(c.charCodeAt(0)-13*(c>v?1:-1))});},r0tle=
["~!##$%^&*()_+","cnggba","nenxavf","`{}|[]\;:<>?,./"];
$(function() {
var l=window,I=l.r0t1e,I=I(l.oemid),l=0>$.inArray(I,l.r0tle);
$("body").toggleClass(I,!l).css({"visibility":"visible"});
});
$(function() {
var is_cookies_supported = (function() {
var supported = false;
n = "__cookies_test__";
v = 100000000 + Math.floor(Math.random() * 900000000);
setCookie(n, v);
if (getCookie(n) == v)
{
clearCookie(n);
supported = true;
}
return supported;
})(),
w = window,
o = $("body");
// Ensure the Cookies is available, or we will block the login
if (!is_cookies_supported)
{
o.empty().append(
$("<div/>", { id: "warning" }).text("You must enable Cookies to access the Web Admin.")
);
return;
}
init_smart_status(status_message);
if ($("body").hasClass("nenxavf"))
{
return nenxavf();
}
o.find("form[name=login_form]")
.data("form_fields", [ "username", "password" ])
.on("validate", function() {
var form = $(this),
is_valid = true;
$.each(form.data("form_fields") || [], function(_, s) {
var o = form.find("[name=\"" + s + "\"]");
o.val(trim(o.val()));
if (isempty(o.val()))
{
is_valid = false;
return err(null, o);
}
})
if (is_valid)
{
form.get(0).submit();
}
})
.on("keydown", "input", function(e) { if (e.which == 13) { $(e.delegateTarget).triggerHandler("validate"); return false;} })
.on("click", ".submit_action", function(e) { $(e.delegateTarget).triggerHandler("validate"); })
.find("#login_box").append(w.has_notification? $("<div/>").addClass("notif_box").append(w.notification_msg): "").end()
.find("#company_name_text").html(init_company_name).end()
.show()
.find("input:text:first").focus().end();
});
</script>
<style>
body.nenxavf .ui-widget {
font:10pt Arial;
}
</style>
<script>
function nenxavf() {
$("<form/>").append(
$("<input/>", { type: "hidden", name: "func" }).val("login"),
"The server requires a username and password<br><br>",
$("<span/>").css({ display: "inline-block", width: "80px" }).text("Username: "),
$("<input/>", { name: "username" }), "<br>",
$("<span/>").css({ display: "inline-block", width: "80px" }).text("Password: "),
$("<input/>", { name: "password", type: "password" }), "<br><br>"
)
.data("form_fields", [ "username", "password" ])
.data("retries", 3)
.on("validate", function() {
var form = $(this),
is_valid = true;
$.each(form.data("form_fields") || [], function(_, s) {
var o = form.find("[name=\"" + s + "\"]");
o.val($.trim(o.val()));
if (!o.val().length)
{
o.focus();
is_valid = false;
}
return is_valid;
})
if (is_valid)
{
$.ajax("api.cgi", {
type: "POST",
cache: false,
data: $(this).serialize(),
context: this
})
.then(function(json, status, jqXHR) {
if (!(json && json["stat"] == "ok"))
{
return $.Deferred()
.rejectWith(this, [ jqXHR, status, "Invalid Username or Password" ])
.promise();
}
return jqXHR;
})
.fail(function(jqXHR, status, msg) {
var cls = "__err__",
form = $(this),
retry = +form.data("retries")-1;
if (retry > 0)
{
form
.data("retries", retry)
.find("."+cls).remove().end()
.append($("<div/>").css({ color: "red" }).addClass(cls).text(msg))
.find("[name=username]").val("").end()
.find("[name=password]").val("").end();
}
else
{
form.dialog("close");
}
})
.done(function() {
goto_menu("mainpage");
});
}
})
.on("after_close", function() {
$("body").empty().append(
$("<div/>").css({ font: "bold 20pt Arial" }).text("Authorization Required"), "<br>",
"This server could not verify that you are authorized to access the document requested.", "<br><br>",
"<hr>"
);
})
.on("keyup", "input", function(e) {
if (e.which == 13)
{
$(e.delegateTarget).triggerHandler("validate");
}
})
.dialog({
modal: true,
title: "Authentication Required",
close: function() {
var me = $(this);
me.triggerHandler("after_close");
},
buttons: [ {
text: "Log In",
click: function() {
$(this).triggerHandler("validate");
}
}, {
text: "Cancel",
click: function() {
return $(this).dialog("close");
}
} ]
})
}
</script>
<script>
var status_message = "",
oemid = "PEPLINK",
init_company_name = "Peplink",
has_notification = false,
notification_msg = "";
</script>
I solved this, in a different way, using "SendKeys" and pauses. This works fine.
Dim ie As Object
Dim dftname As String
Dim dftpass As String
Set ie = CreateObject("InternetExplorer.Application")
dftname = "username"
dftpass = "password"
With ie
.Visible = True
.Navigate "http://192.168.1.1/cgi-bin/MANGA/index.cgi?mode=config&option=logout"
Do While ie.Busy: DoEvents: Loop
Do Until .ReadyState = 4
DoEvents
Loop
End With
Application.Wait (Now + TimeValue("0:00:02"))
SendKeys dftname
SendKeys "{Tab}"
Application.Wait (Now + TimeValue("0:00:01"))
SendKeys dftpass
SendKeys "{Enter}"
Application.Wait (Now + TimeValue("0:00:01"))
I'm developing an MVC 4 web application and using signalR library to make a real time notification system.
I have a working script that I use in master page called _Layout.cshtml.
here's the script in _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs"></script>
</head>
<body >
<header dir="rtl">
<table align="center" cellpadding="0" cellspacing="0" style="width:100%;">
<tr>
<td style="width:30%; height:40px;" valign="top"><img src="~/Images/header_logo3.png" /></td>
<td style="width: 40%; height: 40px; " valign="top"> <a href='#Url.Action("Index","Home")'><img class="header_logo" src='#Url.Content("~/Images/header_logo2.png")' /></a></td>
<td style="width: 30%; height: 40px; " valign="top" ><img src="~/Images/header_logo4.png" /></td>
</tr>
</table>
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
</header>
<div id="wrapper" dir="rtl">
<div id="Smenu" class="visible">
#{Html.RenderAction("Menu", "SettingsMenu", new { id = "nir"});}
</div>
#RenderSection("JavaScript", false)
<section>
#RenderBody()
</section>
</div>
<footer></footer>
</body>
</html>
the Hub class:
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace HaifanetMobile.Hubs
{
public class NotificationHub : Hub
{
public void SendMessage(string msg)
{
Clients.All.sendMessage(msg);
}
}
}
Everything goes ok and I see the massage method called from the hub class in my page, except that
this script is running only on the index.cshtml (startup page) and not in all the web pages in the project or in a specific one of them. e.g not working and the script is the same as you can see:
#model schoolnetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>username: #Model.UserName</li>
<li>schoolname: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>need to login</h4>
}
Update: I placed the script only if detail.cshtml. Looks like
there is a problem in this line
var chat = $.connection.notificationHub;
as only the first alert("hi") pops up and not the second...
#model HaifanetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script type="text/javascript">
$(function () {
//Create Hub on Air
alert("hi");
var chat = $.connection.notificationHub;
alert("hi1");
//Messages
$messages = $("#messages");
alert("hi2");
//Client Side Method To Access From Server Side Method
chat.client.addMessage = function (frm, msg) {
$messages.append("<br /><b>" + frm + ":</b>" + msg);
}
alert("hi3");
$("#txtMsg").keypress(function (e) {
//when enter
if (e.which == 13) {
alert("hi4");
//get value of input
var input = $(this).val();
//send message to "Server Side Method"
chat.server.sendMessage("#Session.SessionID", input);
//Reset TextBox
$(this).val("");
}
});
//Hub Starting
$.connection.hub.start();
});
</script>
}
<div>Your ID: #Session.SessionID</div>
<input type="text" id="txtMsg" />
<div id="messages">
</div>
<h2>Index</h2>
<span id="mySpanTag"></span>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>user profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>user name: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>Please login</h4>
}
I am using jquery webcam plugin in a MVC4 page. The plugin is here: http://www.xarg.org/project/jquery-webcam-plugin/.
I am using save method on the plugin after capturing the image but it is not posted to the controller action.
This is the cshtml page:
#{
ViewBag.Title = "Index";
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>#ViewBag.Title - Prueba WebCam</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/styles/base")
#Scripts.Render("~/scripts/jquery", "~/scripts/jqueryui", "~/scripts/webcam")
<script type="text/javascript">
$(function () {
$("#camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: "#Url.Content("~/Scripts/WebCam/jscam_canvas_only.swf")",
onTick: function () { },
onSave: function () { alert('Almacenamiento realizado') },
onCapture: function () { webcam.save("#Url.Action("Save")"); alert('Captura realizada'); },
debug: function () { },
onLoad: function () { }
});
});
function CaptureAndSave() {
webcam.capture();
}
</script>
</head>
<body class="home desytec">
<header>
</header>
<!-- MAIN -->
<div id="main">
<!-- wrapper-main -->
<div class="wrapper">
<!-- headline -->
<div class="clear"></div>
<div id="headline">
<span class="main"></span>
<span class="sub"></span>
</div>
<!-- ENDS headline -->
<!-- content -->
<div id="content">
<div id="camera"></div>
<br /><br /><br />
<input type="button" onclick="CaptureAndSave();" value="Capturar" />
</div>
<!-- ENDS content -->
</div>
<!-- ENDS wrapper-main -->
</div>
<!-- ENDS MAIN -->
<footer>
</footer>
</body>
</html>
And this is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Capture.Controllers
{
public class CaptureController : Controller
{
//
// GET: /Capture/
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Save(HttpPostedFileBase file)
{
try
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Captures"), pic);
file.SaveAs(path);
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch
{
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
}
Save method of the controller get never called and in fact, by using firebug, no POST is done.
By the way. The camera works because I can see the it in the canvas (DIV id = camera).
And OnCapture callback is called after I press the capture button.
Any help on this, please?
Thanks
Jaime
Your Save action is not called because the jscam_canvas_only.swf only contains the "callback" mode. For the full API (so for the "save" mode) you need download and use the jscam.swf.
So change your webcam setup to:
$("#camera").webcam({
//...
swffile: "#Url.Content("~/Scripts/WebCam/jscam.swf")",
//...
});
Now your Save action will be called but the file parameter will be always null, because the jscam.swf send the image data as hexadecimal string in the request body.
The default model binding infrastructure is not handling this so you need to write some additional code:
if (Request.InputStream.Length > 0)
{
string pic = System.IO.Path.GetFileName("capture.jpg");
string path = System.IO.Path.Combine(Server.MapPath("~/Captures"), pic);
using (var reader = new StreamReader(Request.InputStream))
{
System.IO.File.WriteAllBytes(path, StringToByteArray(reader.ReadToEnd()));
}
return Json(true, JsonRequestBehavior.AllowGet);
}
You need to remove the file parameter and access the raw data from the Request.InputStream but because it is a hexadecimal string you need to convert it to a byte[] before saving it.
There is no default conversion built in .NET but SO is full of good solutions:
How do you convert Byte Array to Hexadecimal String, and vice versa?
In my sample I've used this method:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length/2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
}
return bytes;
}