2

I am trying to fire a Javascript call when an ASP.net user control to an aspx page.
The Web site allows users to add user controls to a page (similar to adding a widget etc to a page like google widgets). But when the control is added the javascript does not fire, only if the page is refreshed will it fire the javascript. IF the next time the website is accessd and the controlis still there the javascript fires too.

Do I need to use the RegisterClientScript method to register the call (setAutoTimer()) on the control load or OnPreRender event.

In the User control I have this at the start of the ascx file:

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        if ($("#alarmList").length) {
            setAutoTimer();
            getData();
       }
    });

    function setAutoTimer() {
        setInterval(getData, 10000);
    }

    function getData() {
        $.ajax({
            type: "POST",
            url: "Service.asmx/getListData
            data: "{'inverterid': '" + "1'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                AjaxSucceeded(msg);
            },
            error: AjaxFailed
        });
    }

    function AjaxSucceeded(result) {
        $("#alarmList").empty();

        $("#alarmsListTemplate").tmpl(result.d)
        .appendTo("#alarmList");
    }

    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }
</script>

2 Answers 2

4

$(document).ready(function () {}); will only run after a full postback occurs (when the DOM is reloaded). I assume you are adding the controls via another AJAX method (in that case document.ready will not fire. You can use the AJAX framework event pageLoad(sender, args) which will fire after both a callback and postback. You can use it like so ..

function pageLoad(sender, args) {
        if (args.get_isPartialLoad()) {
            setAutoTimer();
            getData();
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the tip; I think this has helped.
This worked great for me, but I wanted the javascript to work both before and after the callback, so I removed the 'if (args.get_isPartialLoad())' and it worked like a charm. Thanks, @bleeeah !
0

You can call the method from the javascript that adds the widget to the page.

e.g.

function AjaxSucceeded(result) {
    $("#alarmList").empty();

    $("#alarmsListTemplate").tmpl(result.d)
    .appendTo("#alarmList");

    setAutoTimer();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.