Error with Excel macro for logging into website - vba

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"))

Related

bootstrap-vue multi level drop down

i'm using bootstrap-vue and i have a multi level drop down menu (for categories) . this is official site example :
https://bootstrap-vue.org/docs/components/dropdown
<b-dropdown id="dropdown-1" text="Dropdown Button" class="m-md-2">
<b-dropdown-item>First Action</b-dropdown-item>
<b-dropdown-item>Second Action</b-dropdown-item>
</b-dropdown>
but i don't know how to create a multi level menu (i copy drop downs inside each other but it does not work) ! it has only 1 level drop down example ! how can i create a multi level one ?
tnx
So as I mentioned in my comments you can wrap b-dropdown events and do something custom like this:
window.onload = () => {
new Vue({
el: '#app',
data() {
return {
name: 'BootstrapVue',
isDropdown2Visible: false
}
},
mounted: function () {
this.$root.$on('bv::dropdown::show', bvEvent => {
if(bvEvent.componentId === 'dropdown-2') {
this.isDropdown2Visible = true;
}
})
this.$root.$on('bv::dropdown::hide', bvEvent => {
if(bvEvent.componentId === 'dropdown-2') {
this.isDropdown2Visible = false;
}
if(this.isDropdown2Visible) {
bvEvent.preventDefault()
}
})
}
})
}
body { padding: 1rem; }
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap#4.5.3/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue#2.21.2/dist/bootstrap-vue.css" />
<script src="https://unpkg.com/vue#2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue#2.21.2/dist/bootstrap-vue.min.js"></script>
<div id="app">
<b-dropdown id="dropdown-1" text="Dropdown Button 1" class="m-md-2">
<b-dropdown-item>First Action 1</b-dropdown-item>
<b-dropdown-item>Second Action 1</b-dropdown-item>
<b-dropdown id="dropdown-2" text="Dropdown Button 2" class="m-md-2">
<b-dropdown-item>First Action 2</b-dropdown-item>
<b-dropdown-item>Second Action 2</b-dropdown-item>
</b-dropdown>
</b-dropdown>
</div>
You can try something like this
This snippet contains logic for one level menu.You can edit code as
per your requirement
JSBin Link
new Vue({
el: "#app",
data: {
menu: [
{ title : 'one'},
{ title : 'two'},
{ title : 'three',showSubMenu : false,
children : [
{ title : 'four'},
{ title : 'five'},
]},
]
},
methods : {
toogleItem(index){
if(this.menu[index].children){
if(!this.menu[index].showSubMenu){
this.menu[index].showSubMenu = true
} else {
this.menu[index].showSubMenu = false
}
}
}
}
})
.sub-menu{
position: absolute;
min-width: 10rem;
padding: .5rem 0;
margin: .125rem 0 0;
font-size: 1rem;
color: #212529;
text-align: left;
list-style: none;
background-color: #fff;
background-clip: padding-box;
border: 1px solid rgba(0,0,0,.15);
border-radius: .25rem;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<!-- Load required Bootstrap and BootstrapVue CSS -->
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.min.css" />
<!-- Load polyfills to support older browsers -->
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>
<!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue#latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.min.js"></script>
<!-- Load the following for BootstrapVueIcons support -->
<script src="//unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue-icons.min.js"></script>
</head>
<body>
<div id="app">
<b-dropdown id="dropdown-1" text="Dropdown Button" class="m-md-2">
<b-dropdown-item
v-for="(item,index) in menu"
:key="index"
#mouseover.native="toogleItem(index)"
#mouseout.native="toogleItem(index)">
<span>{{item.title}} <b-icon-caret-down-fill :scale="0.6" v-if="item.children"></b-icon-caret-down-fill></span>
<div v-if="item.children" class="sub-menu" v-show="item.showSubMenu">
<b-dropdown-item v-for="(item,index) in item.children" :key="index">{{item.title}}
</b-dropdown-item>
</div>
</b-dropdown-item>
</b-dropdown>
</div>
</body>
</html>

dojo datagrid autoheight not working when programmatically defined

The following code builds 3 datagrids, 2 via markup and one via code.
When you press the "autoheight!" button only the markup datagrids resize.
I don't understand why the code datagrid does not work. As far as i can see, the same attributes are being initialized.
Thanks
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://js.arcgis.com/3.13/dijit/themes /claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.13/dojox/grid/resources/claroGrid.css">
<script>dojoConfig = {parseOnLoad: true}</script>
<script src="http://js.arcgis.com/3.13/"></script>
<script>require(["dojo/parser", "dijit/layout/TabContainer", "dijit/layout/ContentPane"]);</script>
<meta charset="UTF-8">
<title>alubia</title>
<script type="text/javascript">
var test_store;
var layout = [
{name:"id", field:"id", width: '165px', noresize: 'true'},
{name:"data", field:"data", width: '125px', noresize: 'true'}
];
function loadData(gridId, divId) {
require(['dojo/data/ItemFileWriteStore', 'dojox/grid/DataGrid'], function(ItemFileWriteStore, DataGrid) {
var mi_data = {
items : [],
identifier:"id"
};
for (var i = 0; i < 22; i++) {
mi_data.items.push({id: ""+i, data:"111 ! "+ i});
}
test_store = new ItemFileWriteStore({data: mi_data});
if (divId != null) {
var grid = new DataGrid({
id : gridId,
store : test_store,
structure : layout,
rowSelector : '0px',
autoHeight : false
});
grid.placeAt(divId);
grid.startup();
}
});
}
function fitHeight(gridId) {
var grid = dijit.byId(gridId);
grid.set('autoHeight', true);
grid.set('autoWidth', false);
grid.update();
}
loadData("grid", null);
loadData("grid2", "grid2Div");
loadData("grid3", null);
</script>
</head>
<body class="claro" style="font-family:sans-serif; font-size:12px;">
<button onclick="fitHeight('grid'); fitHeight('grid2'); fitHeight('grid3');">autoheight!</button>
<div id="grid2Div" style="height: 7em;" ></div>
<div id="grid" style="height: 7em;" data-dojo-id="grid" dojoType="dojox.grid.DataGrid" autoHeight="false" store="test_store" structure="layout" ></div>
<div id="grid3" style="height: 7em;" data-dojo-id="grid3" dojoType="dojox.grid.DataGrid" autoHeight="false" store="test_store" structure="layout" ></div>
</body>
</html>
again, dojo is a horrible tool. going to datatables (jquery plugin). the sun shines again.

Controller cannot go to server Side in mvc

I am doing my application in MVC. I have registration and Login links. I have implemented Login link in all pages. If i click login it is moving to the server side(controller) and opening. MY problem is from whatever page i click login it needs to open in the same window in popup. It means that it doesn't go the server side.
My code is
#model SYTMain.Models.Login
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout_for_login.cshtml";
//Layout = "~/Views/Shared/_Layout_for_login_registration .cshtml";
}
<center><h2>Login</h2></center>
<div id="dialog-modal" title="Login">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Login failed. Check your login details.");
<div style=" margin-bottom: 400px;">
<fieldset>
<legend>Login</legend>
<div class="editor-label">
#Html.LabelFor(u => u.EmailID)
</div>
<div class="editor-field">
#Html.TextBoxFor(u => u.EmailID)
#Html.ValidationMessageFor(u => u.EmailID)
</div>
<div class="editor-label">
#Html.LabelFor(u => u.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(u => u.Password)
#Html.ValidationMessageFor(u => u.Password)
</div>
#*<div class="editor-label">
#Html.CheckBoxFor(u => u.RememberMe)
#Html.LabelFor(u => u.RememberMe)
</div>*#
<input type="submit" value="Log In" />
</fieldset>
</div>
}
</div>
Layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
#*<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />*#
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script src="~/Scripts/Popup/jquery-1.5.1.min.js"></script>
<script src="~/Scripts/Popup/jquery-ui-1.8.11.js"></script>
#Scripts.Render("~/bundles/modernizr")
<script>
$(function () {
$("#dialog-modal").dialog({
width: 400,
height: 200,
show: {
effect: "shake",
duration: 100
},
hide: {
effect: "explode",
duration: 1000
}
});
});
</script>
</head>
<body style=" margin: 0px auto;overflow: scroll; overflow-x: hidden; /* width: 1330px; */height: auto;">
<div class="layoutouter">
<div class="layoutlogo">
#Html.ActionLink("Sell Your Time", "Index", "Home")
</div>
<div class="layoutmenu">
#if (!string.IsNullOrEmpty(Convert.ToString(Session["EmailID"])))
{
#Html.ActionLink("Signout", "Logout", "CU")
}
else
{
#Html.ActionLink("Register", "Create", "CU")
}
</div>
<br /><br />
#*<strong>Welcome #Session["EmailID"]</strong>*#
<div>
#RenderSection("featured", required: false)
</div>
</div>
<div style="width:1000px ; margin:0px auto;">
#RenderBody()
</div>
<div class="layoutfooter">
<div class="layoutfooter_data">
<div class="layout_location">
#Html.ActionLink("Change Location", "yy", "zz")
<span>|</span>
</div>
<div class="layout_feedback">
#Html.ActionLink("Feedback", "yy", "zz")
<span>|</span>
</div>
<div class="layout_help">
#Html.ActionLink("Help", "yy", "zz")
</div>
</div>
<div class="footer_copy">
<p>© #DateTime.Now.Year - acutesoftsys</p>
</div>
<div class="footer_condition">
<div class="footer_term">
<span>|</span>
#Html.ActionLink("Term & Condition", "", "")
</div>
<div class="footer_policy">
#Html.ActionLink("Privacy Policy", "yy", "zz")
</div>
</div>
</div>
#RenderSection("scripts", required: false)
</body>
</html>
My controller code is
[HttpPost, ValidateInput(false)]
public ActionResult Login(Login loginDetails)
{
if (ModelState.IsValid)
{
using (SYTEntities context = new SYTEntities())
{
var LoginUser = context.tblUsers.Where(a => a.EmailID == loginDetails.EmailID && a.Password == loginDetails.Password).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(loginDetails.EmailID, loginDetails.RememberMe);
Session["EmailID"] = LoginUser.EmailID;
Session["UserID"] = LoginUser.UserID;
return RedirectToAction("CalendarView", "Appt", new { CustomerUserid = Session["UserID"]});
// return RedirectToAction("Details/" + Session["UserID"]);
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
}
return View(loginDetails);
}
Please help me to achieve this .
Thanks in Advance
Your controller code should look something like this
public ActionResult YourControllerAction( int Userid )
{
//Add your logic here
return PartialView( "UserDetails", model );
}
Your partial view should look like this
#model Models.Login
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>login</title>
</head>
<body>
<div>
/*Your markup here*/
</div>
</body>
</html>
Your jQuery code should look something like this.
$('#loginlinkid').on('click', function(evt) {
var $loginDiv = $('#PopUpDiv')
$.get(urlOfYourAction, function(data) {
$loginDiv.replaceWith(data);
});
//Add code to open popup here. eg..bootstrap modal dialog
});
Similar post here Render a partial view inside a Jquery modal popup on top of a parent view

SignalR client script runs only in index page

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>
}

Opera extension error "Uncaught exception: ReferenceError: Security violation"

I am working on an opera extension. The extension have a popup that will open a website in it.
I get the below error at "xhr.send()" in popup.html file and i can't able to remove it.
"[4/14/2013 12:51:19 PM] JavaScript -
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html Inline
script thread Uncaught exception: ReferenceError: Security violation
Error thrown at line 30, column 16 in fetchGames() in
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
xhr.send(); called from line 32, column 12 in widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
fetchGames(); "
My config file is as below:
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" id="http://www.example.org/helloworld">
<name>Hello Extensions!</name>
<description>A simple hello world example</description>
<author href="http://www.twitter.com/dstorey/" email="dstorey#opera.com">David Storey, Opera Software</author>
<icon src="icons/icon-64.png"/>
</widget>
My index.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Hello World!</title>
<meta charset="UTF-8">
<script>
window.addEventListener( 'load', function(){
var theButton;
var ToolbarUIItemProperties = {
disabled: false,
title: 'Hello World',
icon: 'icons/icon-18.png',
popup: {
href: 'popup.html',
width: 500,
height: 500
}
}
theButton = opera.contexts.toolbar.createItem(ToolbarUIItemProperties);
opera.contexts.toolbar.addItem(theButton);
}, false );
</script>
</head>
<body>
</body>
</html>
My popup.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
background-color: #efefef;
}
</style>
<script>
function fetchGames() {
alert('hello');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = (xhr.responseText);
document.getElementById('list_games').innerHTML = data;
//callback(data);
}
else {
alert('No Games Found');
window.close();
}
}
}
var url = 'http://www.anatomic.us/generate-xml';
xhr.open('GET', url, true);
xhr.send();
};
fetchGames();
function submitForm(obj)
{
var searchKey = document.getElementById('sp').value;
if(searchKey!=null && searchKey!='')
{
obj.setAttribute('action', 'http://www.3d-game.co/'+searchKey);
return true;
// chrome.tabs.create({url: 'http://www.3d-game.co/'+searchKey});
}
else
{
alert('Please Enter your search item');
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- <div class="header">
<img src="icon.png">
</div>
<br />-->
<div id=content>
<div style='padding-left:10px;'>
<form id=sf method=post action="http://www.3d-game.co/search/" onSubmit="return submitForm(this);" target="_blank">
</form>
</div>
<div id=cat_content>
<div id="list_games" class=list_games>
<img src="loader.gif" border="none" />
<div class="ajax-loader">
<img src="loader.gif" border="none" />
</div>
</div>
</div>
</body>
</html>
Plz help me in removing it.
Add following in the header of the file from where you are fetching the data:
Access-Control-Allow-Origin: *
in config.xml file add this line: to allow any domain httprequest before tab, this solve the problem, if problems persist, open in opera browser tab "opera:config" and select "Users Prefs" and check "Allow File XMLHttpRequest" and restart. if have problem i can send you my opera extension working fine...