Web form javascript image refresh with interval - javascript

Please help me to refresh periodically an image in a web form (asp.net).
Here is my code. The image is not refreshing. Thank you in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.11.0.min.js">
$(document).ready(function () {
var refreshId = setInterval(function () {
var obj = document.getElementById("<%=Image1.ClientID%>");
var src = obj.src;
var pos = src.indexOf("?");
if (pos >= 0) {
scr = src.substr(0, pos);
}
var date = new Date();
obj.src = src + '?v=' + date.getTime();
return true;
}, 10000);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/sOverview.png" />
</div>
</form>
</body>
</html>
and the code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Image1.ImageUrl = Image1.ImageUrl + "?" + DateTime.Now.ToLongTimeString()
End Sub

A script element gets its script from either the text node inside it, or the URL of the src attribute. Not both.
If you want to load two scripts (one from a URL and on in the text node) then you need two script elements.

Related

get the Page's HiddenField Value in UserControl on Page

I want to read the Page(.aspx) Hiddenfield Value in the User Control that is placed on that Page and process some logic.
FOr eg: I have a hidden field x on a Page. The Page has many user controls and I want to access this hidden field (x) in those User Controls where value of x will be set by a Javascript in the Page.
I am trying to find the HiddenControl and read its value from codebehind of usercontrol(.ascx.cs) but always get null.
HiddenField colname = UIUtils.FindControlRecursive(this.Parent.Page, "MainContent_AssignedTo_ColName") as HiddenField;
The ID is same as the hiddenfield on client Side. I tried this.Parent and this.Parent.Parent for the first argument too but no luck.
what am I missing here.
Here is my aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestFindControl._Default" %>
<%# Register Src="ReadHiddenField.ascx" TagName="Assign" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server" Value="10">
</asp:HiddenField>
<asp:placeholder ID="Placeholder1" runat="server"><uc1:Assign id="test" runat="server"></uc1:Assign> </asp:placeholder>
</div>
</form>
</body>
</html>
and here is my code behind on control:
protected void Page_Load(object sender, EventArgs e)
{
HiddenField test = (HiddenField)Page.FindControl("HiddenField1");
var j = test.Value;
}
Try:
HiddenField colname = (HiddenField)Page.FindControl("The id of control");
private void GetParentPageHiddenField()
{
System.Web.UI.WebControls.HiddenField ParenthiddenField = null;
Control ctl = this.Parent;
while (true)
{
ParenthiddenField = (System.Web.UI.WebControls.HiddenField)ctl.FindControl("ParentPageHiddenFieldID");
if (ParenthiddenField == null)
{
if (ctl.Parent == null)
{
return;
}
ctl = ctl.Parent;
continue;
}
break;
}
var parentHiddenFieldValue=ParenthiddenField.Value;
}

Previous pages visible even after Logging Out. The Page is Cached

After a User Logs-out the page is redirected to Login.aspx page but after pressing the Back Button he is able to see the previous pages.
I have already used JavaScript to disable the Back Button
My Logout.aspx is as Follows:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Logout.aspx.vb" Inherits="Logout" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE" />
<title>Untitled Page</title>
<script type="text/javascript" language="Javascript">
history.go(1);
</script>
</head>
<body onload="changeHashOnLoad(); ">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
<script type = "text/javascript">
function disableBackButton() {
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
<script type="text/javascript">
function noBack() { window.history.forward() }
noBack();
window.onload = noBack;
window.onpageshow = function(evt) { if (evt.persisted) noBack() }
window.onunload = function() { void (0) }
</script>
</html>
And Logout.aspx.vb as Follows:
Imports System.Data.SqlClient
Imports System.Data
Partial Class Logout
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strHostName As String = System.Net.Dns.GetHostName()
Dim clientip As String = GetIpAddress()
Dim params() As SqlParameter = New SqlParameter(6) {}
params(0) = New SqlParameter("#compname", strHostName)
params(1) = New SqlParameter("#ip_add", clientip)
params(2) = New SqlParameter("#mac_add", "")
params(3) = New SqlParameter("#login_id", Session("login").ToString())
params(4) = New SqlParameter("#user_name", Session("topusr").ToString())
params(5) = New SqlParameter("#login_status", "Logout Success")
params(6) = New SqlParameter("#counted", "Y")
Dim cnString As String = ConfigurationManager.ConnectionStrings("patravaliConnectionString").ToString
Dal.ExecuteNonQuery(cnString, CommandType.StoredProcedure, "sp_audit1", params)
Response.Cookies.Add(New HttpCookie("Asp.Net_SessionId", ""))
Response.Cookies.Add(New HttpCookie("ASMSAUTH", ""))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(Now.AddSeconds(-1))
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
System.Web.Security.FormsAuthentication.SignOut()
Response.Redirect("login.aspx")
'FormAuthentication.Signout()
Response.Buffer = True
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1D)
Response.Expires = -1500
Response.CacheControl = "no-cache"
'Response.Buffer=<SPAN style="COLOR: blue">true;<o:p></o:p>
'Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
'Response.Expires =-1500;
'Response.CacheControl = "no-cache";
'if(Session["SessionId"] == null)
'{
' Response.Redirect ("WdetLogin.aspx");
'}
'}
'
Session("topusr") = ""
Session("topdept") = ""
Session("usercd") = ""
Session("branch") = ""
Session("prt") = ""
Session("deptcd") = ""
Session.Abandon()
Session.Abandon()
Session.Clear()
Session.RemoveAll()
Application("genericstr") = "uu"
Response.Redirect("~/Login.aspx")
End Sub
Public Function GetIpAddress() As String
Dim stringIpAddress As String
stringIpAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If stringIpAddress Is Nothing Then
'may be the HTTP_X_FORWARDED_FOR is null
stringIpAddress = Request.ServerVariables("REMOTE_ADDR")
'we can use REMOTE_ADDR
Dim add As String = HttpContext.Current.Request.UserHostAddress
End If
Return stringIpAddress
End Function
End Class
The previous page which is viewed is just a Cache because any changes made on that page redirects it to home page.
But all previous pages contain information which should only be visible to the Logged-In person.

`getJSON()` of jQuery not calling same page's function to get JSON data

I want to use getJSON()'s demo to show its use insetead of $.ajax.
I've till created the following code.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test_JSON.aspx.vb" Inherits="Test_HTML" %>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test HTML</title>
<script src="Script/jquery-1.9.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Name:
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnView" Text="View Label of Name" />
</div>
</form>
<script type="text/javascript">
function getJsonData() {
debugger;
$("#btnView").val = $("#txtName").val();
var objJson = {};
objJson["name"] = $("#txtName").val();
return objJson;
}
$("#btnView").click(function(event) {
debugger;
$.getJSON('/Test_JSON.aspx/getJsonData', function(result) {
debugger;
$('<p> APPEND TEXT </p>').appendTo('#btnView');
$('<p> PREPEND TEXT </p>').prependTo('#btnView');
});
});
</script>
</body>
</html>
VB code for PageMethod
Imports Newtonsoft.Json
Partial Class Test_HTML
Inherits System.Web.UI.Page
<Web.Services.WebMethod()> _
Public Shared Function getJsonData(ByVal name As String) As String
Dim jsonString As String = String.Empty
Dim dt_jsonData As New DataTable
Dim dr As DataRow = dt_jsonData.NewRow
Try
dt_jsonData.Columns.Add("name")
dr("name") = name.ToString.Trim()
dt_jsonData.Rows.Add(dr)
If dt_jsonData.Rows.Count <> 0 Then
jsonString = JsonConvert.SerializeObject(dt_jsonData)
End If
Catch ex As Exception
Return ""
Exit Function
End Try
Return jsonString
End Function
End Class
I want to get data from getJsonData(). But my getJSON() is not getting executed with URL. Is there any other way I should use this?
All I need to do is:
1> Enter text in text box
2> Click on button
3> Get textbox's value through getJSON() method and use it somewhere else.
4> And also use appendTo and prependTo methods for demo.

Javascript function returns variables as undefined

I am dynamically including a javascript file into a html page, which works fine. But when I run the function 'tryData' from the file the variables return as undefined. I've been looking for hours can't find a similar problem anywhere, does anyone know what the problem is?
function in external file:
function tryData(id, size){
document.getElementById('content').innerHTML = '<iframe src="http://domain.com/feeds/'+id+'/'+size+'/" id="frame"></iframe>';
if(window.data){
clearInterval(timer);
data();
}
}
the line I am using to call it:
tryData(131, 'large');
I know that the function is running because the frame is inserted as expected, but there's no content as the URL for the frame reads 'domain.com/feeds/undefined/undefined/', instead of 'domain.com/feeds/131/large/'.
Thanks in advance for any help :)
Here is an example of a html page with the function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="robots" content="NOINDEX,NOFOLLOW" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<!-- Widget -->
<div id="content"></div>
<script>
(function(d, s) {
var js = d.createElement(s), ins = d.getElementsByTagName(s)[0];
js.src = "http://domain.com/feeds/insert.js";
ins.parentNode.insertBefore(js, ins);
tryData(131, 'large');
}(document, 'script'));
</script>
<!-- Widget End -->
</body>
</html>
here is the js file:
function data(){
var u;
u = document.URL;
$.post("http://domain.com/data.php", { u: u} );
}
function tryData(id, size){
document.getElementById('lsb').innerHTML = '<iframe src="http://domain.com/feeds/'+id+'/'+size+'/" id="frame"></iframe>';
if(window.data){
clearInterval(timer);
data();
}
}
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
timer = setInterval(tryData, 100);
Where are you passing the parameters?
Try this:
timer = setInterval(function(){
tryData(131, 'large');
}, 100);

Register and execute a JavaScript function in a ASP.NET Page_Load event

How can I register AND execute that JavaScript function in ASP.NET on a Page_Load event so my textbox content gets validated and if nothing is in there I can disable a save button?
function Validate(source, arguments)
{
}
Use ClientScriptManager.RegisterStartupScript
See here for example
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> alert('Hello World!') </");
cstext1.Append("script>");
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RegisterStartupScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Hope this helps

Categories