how can I solve this JavaScript runtime error? - javascript

I have got an old ASP.NET web page. When I press F5, Visual Studio is giving me error:
0x800a138f - JavaScript runtime error: Unable to get property 'txtAppl' of undefined or null reference.
HTML page,
<%# Page Language="C#" Debug="true" %>
<script runat="server" src="uzpo2003_tbbuild.cs"></script>
<html>
<head>
<title></title>
<script type="text/javascript" src="uzpo2003_client.js"></script>
</head>
<body onload="form_load();">
</body>
</html>
uzpo2003_client.js,
function form_load() {
if (document.formSelect.txtAppl.value == -99999999)
return null;
}
uzpo2003_tbbuild.cs,
public class TableBuild
{
StringBuilder output = new StringBuilder();
public string tblBuilder(string department, string un)
{
int dept = int.Parse(department);
string dom;
dom = "<center><table border='0' style='font:14pt;' bgcolor='#A7C7B7'>";
dom += "<input type = 'text' name = 'txtAppl' value = '' size=16 id = 'Text1'></P>";
return output.ToString();
}
}
How can I solve this problem?

Related

Getting javascript error for large data in body of mailto function

I want to show data stored in Array-list in body of Mailbox. User can then add mail ids in To: according to his/her convenience and send the mail.
But its throwing JavaScript error when large amount of data is sent to body.
Here is the test code of .aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function mail()
{
var array_store;
array_store = document.getElementById("array_store");
var vs = array_store.value;
window.location.href = "mailto: &body=" + encodeURIComponent(decodeURIComponent(vs));
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button_mail" runat="server" Text="OpenInMailBox" OnClientClick="mail()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
Code of .CS page :
public partial class mailto_check : System.Web.UI.Page
{
protected System.Text.StringBuilder ArrayStore = new System.Text.StringBuilder();
string str = "";
protected void Page_Load(object sender, EventArgs e)
{
ArrayList al = new ArrayList();
al.Add("Test1");
al.Add("hello ");
al.Add("Testing");
try
{
for (int y = 0; y < al.Count; y++)
{
str = al[y].ToString();
this.ArrayStore.Append(str+",%0D");
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
for large data I tested it by adding values to array-list.
Please help me with this.
Thanks in advance for positive answers.

Get value from html input text type textbox as string and pass it to C# hashtable being used in aspx

The textbox is defined as html input text type and takes input from the users. This value is needed to pass as key to hashtable defined in aspx.cs file being used in aspx file. But the correct value is not being given and an exception is being thrown. Any help in this regard would be helpful. Thanks
The code is as follows:
<% =Hashtable[document.getElementbyId("Textbox").Value]%>
document.getElementbyId("Textbox").Value is not giving the correct output. If it is replaced by a string value acting as key then it works fine. The only problem is getting the string value from textbox.
First include jquery in head section
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
Try below code to read textbox value :
First read text box value using
var key = $("[id$=Textbox]").val();
and see if value is present in texbox if present use this to read hash value
<% =Hashtable[key]%>
Try this it worked for me :
aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function GetHashtable() {
alert("<% = hashtable[this.test] %>");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Code behind :
public partial class _Default : System.Web.UI.Page
{
protected int test;
public Hashtable hashtable = new Hashtable();
static Hashtable sHashtable = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sHashtable[1] = "One";
sHashtable[2] = "Two";
sHashtable[13] = "Thirteen";
}
}
protected void txtKey_TextChanged(object sender, EventArgs e)
{
test = Convert.ToInt32("0" + txtKey.Text);
hashtable = sHashtable;
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
}
}

WebBrowser not running javascript

I'm utilizing a System.Windows.Forms.WebBrowser (used in a separate .dll file) from my WPF application in order to print some HTML content in the background.
My problem is that the HTML elemnts are not being affected by the javascript in the page.
I know that there are no errors in the page because that if I copy its content after the DocumentCompleted event and paste it into a plain HTML file the script works.
My HTML template:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
function loaded() {
document.getElementById("content").innerHTML = "after javascript";
}
</script>
</head>
<body onload="loaded()">
<h1 id="content">before javascript</h1> <!--<= This value does not change-->
</body>
</html>
I use this HTML as follows:
private void PrintTest()
{
string curDir = Directory.GetCurrentDirectory();
string fullPath = Path.Combine(curDir, "PrintDocs\\HTMLPage1.html");
string html = File.ReadAllText(fullPath);
HtmlPrint.Print(html);
}
public static class HtmlPrint
{
public static void Print(string html, string documentTitle = "")
{
var wb = new System.Windows.Forms.WebBrowser { DocumentText = html };
wb.DocumentCompleted += wb_DocumentCompleted;
}
private static void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
var wb = ((System.Windows.Forms.WebBrowser)sender);
wb.Print();
wb.Dispose();
}
}
What am I missing here?
You forgot the Braces in onload:
<body onload="loaded()">
As mentioned in my comments you can call the InvokeScript() method from your C# code and pass in your js function name as which should do the trick.
wb.Document.InvokeScript("loaded");
I think you have to change onload="loaded" to onload="loaded()"

`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 error: function XXXX() not defined

I added a javascript function in a page
<head>
<script type=text/javascript>
function show_Alert(error)
{
alert(error);
}
</script>
</head>
and on button click I am doing this
Protected void btn_Click(object o,Eventargs e)
{
StringBuilder str = new StringBuilder();
str.AppendLine("show_Alert('XYZ error')");
ClientScript.RegisterStartupScript(GetType(),"Alert",str.ToString(),true);
}
But it throws JS error show_Alert is not defined :(
Any Idea, what is wrong here??
Thanx
Your script tag is wrong.
Change it to
<script type="text/javascript">
However, I don't think that's the issue.
I suspect that RegisterStartupScript is emitting its <script> block before the one with your function, so that it ends up calling the function before it exists.
Check where each <script> is in the rendered source.
Make sure your <script> element is valid, like this:
<head>
<script type="text/javascript">
function show_Alert(error)
{
alert(error);
}
</script>
</head>
If it's not well formed, or the type is unrecognized (your case has both) then the script inside will be ignored, since the browser doesn't know how to handle it.
Here's an example:
<%# Page Language="C#" %>
<script type="text/C#" runat="server">
protected void BtnClick(object sender, EventArgs e)
{
var str = "XYZ Error";
var script = new StringBuilder();
script.AppendFormat("showAlert('{0}');",
HttpUtility.JavaScriptStringEncode(str)
);
ClientScript.RegisterStartupScript(GetType(), "alert", script.ToString(), true);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function showAlert(error) {
alert(error);
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:LinkButton ID="Btn" runat="server" Text="Click me" OnClick="BtnClick" />
</form>
</body>
</html>
A very important thing to pay attention to is to properly encode the string you are passing to the showAlert function. Notice that it is encoded:
script.AppendFormat("showAlert('{0}');",
HttpUtility.JavaScriptStringEncode(str)
);
If you don't encode it and the string contains some special characters like ' for instance, your script will break.

Categories