Javascript error: function XXXX() not defined - javascript

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.

Related

Calling Java function within Javascript in JSP application

I would like to access a variable and a set of functions from within a javascript segment. I have two files:
testJSP.jsp
<%#page import="test.tester"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String thing = "Exciting String";
tester testy = new tester(thing);
%>
<input type="submit" onclick="test()" value="Sample Text" />
<div id="testDiv" >Boring String</div>
<script language="javascript" >
funciton test() {
document.getElementById("testDiv").innerHTML = <%=testy.getString()%>;
}
</script>
</body>
</html>
tester.java
package test;
public class tester {
private String privy;
public tester(String testString) {
privy = testString;
}
public String getString() {
return "new " + privy;
}
}
Essentially, when the button is clicked, I want the element with id "testDiv" to be changed according to the function in the java file. I may be overlooking a very simple method, or perhaps there is a far more complex way of approaching this seemingly simple problem.

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

`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.

How to call javascript function from vbscript

how to call javascript function from vbscript.
i wrote like this
<script type="text/vbscript">
jsfunction()
</script>
<script type="text/javascript">
function jsfunction()
{
alert("Hello")
}
</script>
but it is showing that type mis match how to achieve it. please help me.
Thank you,
Mihir
Assuming you want this client side as opposed to ASP;
If you place the JScript block before the VBScript block (or wire the call to a load event) that will work fine. (IE only of course)
...
<head>
<script type="text/vbscript">
function foo
call jsfunction()
end function
</script>
<script type="text/javascript">
function jsfunction()
{
alert("hello");
}
</script>
</head>
<body onload="foo()">
...
Calling a VBScript function from Javascript
Your VBScript:
Function myVBFunction()
' here comes your vbscript code
End Function
Your Javascript:
function myJavascriptFunction(){
myVBFunction(); // calls the vbs function
}
window.onload = myJavascriptFunction;
Alternatives (incompatible in some IE versions):
// This one:
window.onload = function(){ myVBFunction(); }
// This will also work:
window.onload = myVBFunction();
// Or simply:
myVBFunction();
// From a hardcoded link, don't write a semicolon a the end:
link
Inversed:
Calling a Javascript function from VBScript
Function myVBFunction()
myJavascriptFunction()
End Function
Try this ...
<%# Language=VBScript %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<script language="JavaScript" >
function jsfunction()
{
alert("Hello")
}
</script>
<%
Response.Write "Calling =" jsfunction() "."
%>
</BODY>
</HTML>
Instead of alert we should write return which is in turn print the values on page using response.write-
code is below -
<%# Language=VBScript %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<script language="JavaScript" runat="server">
function test() {
return "Test";
}
</script>
<%
Response.Write "Value returned =" & test() & "."
%>
</BODY>
</HTML>

How to call Onload function in the Main page as well as #include file inner.jsp page

I have two pages one is the main page and the another one is the inner page:
Page names: main.jsp , sidebar.jsp
I want to call the onload function on both of these pages. Is that possible. If yes How?
Below is the code for main.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# include file="/pages/common/init.jsp"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags"%>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>J.C. Taylor - Broker Website</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="/css/default.css" media="screen" type="text/css" />
</head>
<body onload="prepopulateFields();load(17);">
<s:form name="continue" id="continue_id" action="continue" method="POST" validate="true" enctype="multipart/form-data">
<div id="wrapper">
<div id="main">
<div id="sidebar">
<%# include file="/pages/common/sidebar.jsp"%>
<span class="clearIt"></span>
</div>
The sidebar.jsp is:
<body onload="setSelected();">
//Some static content here
</body>
So Basically I want is to call prepopulateFields() Javascript method which belongs to onload() event of the main .jsp page and setSelected() which belongs to onload() method of the sidebar.jsp symulatneously and separately.
I know I can call the setSelected(); method inside the prepopulateFields() method but that I dont want to do. All I want is when the page is loaded both the onload functions should be called separately.
If you have some suggestions please do let me know!
I know I am being little bit ridiculous here but if I could do that My job will be very easy.
i don't think you can call more than one onload function.
best way is to call the method from already called function
function prepopulateFields(){
if //condition which check the current page where you want other onload function
setSelected();
}
<body onload="prepopulateFields();load(17);">
</body>
You cannot nest HTML <body> elements, it would only malform HTML.
Best is to put it as a <script> at the bottom of sidebar.jsp.
<script type="text/javascript">setSelected()</script>
If you use firebug to inspect the rendered html page of main.jsp. You would see there is only one < body > element. The < body > element in your sidebar.jsp is not rendered since it will malform HTML as html or body not allowed in included jsp.
Be careful that the included file does not contain <html>, </html>, <body>, or </body> tags
The solution is:
either put your setSelected() into main.jsp body onload event if the sidebar.jsp is always loaded;
or do as BalusC suggested.
window.onload = codeAddress; should work. Here's a demo. And the full code:
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
Put the class definition in the parent jsp, and instantiate as many onloads as you need in the includes.
<SCRIPT>
// this portion was placed above the Class definition for convenience.
// make sure the Class definition gets loaded first in your code.
new OnLoad(function(){
alert("document loaded");
},100);
</SCRIPT>
...
<SCRIPT>
// Class Definition
OnLoad = function(taskFunction,miliseconds) {
var context = this;
context.cnt = 0;
context.id = null;
context.doTask=taskFunction;
context.interval = function() {
if(document.readyState == "complete"){
try{ context.stop();} catch(e){ throw new Error("stop error: " + context.id); }
try{ context.doTask();} catch(e){ throw new Error("load error: " + context.id); }
}
};
context.start = function(timing) {
if(context.id && context.id!=null)
context.stop();
context.cnt=0;
context.id=setInterval(context.interval,timing);
};
context.stop = function() {
var _id = context.id;
clearInterval(context.id);
context.id=null;
};
context.start(miliseconds ? miliseconds : 100);
};
</SCRIPT>

Categories