UserED
UserED

Reputation: 33

Script is not recognized inside my aspx page

I have this script

        <script type="text/javascript">
        var request;
        function GetDataUsingAJAX() {
            var value = document.getElementById("search").value;
            request = new XMLHttpRequest();
            request.onreadystatechange = ProcessResponse;
            request.open("GET", "SearchAjax.aspx?searchValue=" + value, true);
            request.send();
        }
        function ProcessResponse() {
            if (request.readyState == 4 && request.status == 200) {
                document.getElementById("result").innerHTML = request.responseText;
            }
        }
</script>

And this button which should call the script:

 <asp:Button runat="server" Text="Search" OnClick="GetDataUsingAJAX()" CssClass="btn btn-default" />

All of it is in the same page (aspx page).

I keep getting this error :

Compiler Error Message: CS1061: 'ASP.search_aspx' does not contain a definition for 'GetDataUsingAJAX' and no extension method 'GetDataUsingAJAX' accepting a first argument of type 'ASP.search_aspx' could be found (are you missing a using directive or an assembly reference?)

It can't find GetDataUsingAJAX().

How can this be solved?

Upvotes: 0

Views: 297

Answers (2)

Dacker
Dacker

Reputation: 892

If you want to trigger an AJAX call you don't need to use the Button.

The Button is a WebControl used for submitting the form. You don't want to submit anything, but you want something done locally using AJAX.

In your case you don't have to set the OnClick but the OnClientClick. The OnClientClick for a normally is there todo something special before submitting. You probably need to return false to actually stop the submit, otherwise your AJAX call won't be processed as expected, since the page is in a new roundtrip itself. You can stop the submit by making GetDataUsingAJAX() return false. Then change the call to:

OnClientClick="return GetDataUsingAJAX();"

An alternative to the Button without any serverside requirements and hence no long clientID and viewstate is a pure hyperlink:

<a href="" onclick="return GetDataUsingAJAX();" class="btn btn-default">Search</a>

If disabling the submit doesn't solve your issue either, try adding an alert as first line in GetDataUsingAjax() to see whether it actually gets called. If not the script may not be on your page.

Upvotes: 0

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25445

OnClick is the attribute used to indicate with method in your code-behind file to be executed on the server when the button is clicked.

You're looking for OnClientClick which executes javascript in the browser.

Upvotes: 3

Related Questions