BreakHead
BreakHead

Reputation: 10672

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

Upvotes: 1

Views: 8410

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

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.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630627

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.

Upvotes: 2

SLaks
SLaks

Reputation: 888223

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.

Upvotes: 4

Related Questions