Laguna
Laguna

Reputation: 3876

How to make javascript execute after using jQuery to dynamically load user control to div?

I have a Web User Control with javascript and css blocks. I'm using jQuery to dynamically load it into the main page. How do I make the alert('haha') to execute when the user control is loaded into the div called "divTable"?

In my .ascx file, I have

<script type="text/javascript">
  function pageLoad(sender, args) {
    alert('haha');
  }
</script>

In the .aspx file, I have

<script type="text/javascript">
    $(function () {
        $('button').click(GetTable);
    });

    function GetTable() {
        debugger;
        var id_1 = $('#txtID1').val();
        var id_2 = $('#txtID2').val();
        $.ajax({
            url: 'Services/Data.svc/RenderUC',
            data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                debugger;
                $('#divTable').html(data);
            },
            error: function showError(xhr, status, exc) {
                debugger;
                alert('error');
            }
        });
    }
</script>

In the .svc file, I have

    [OperationContract]
    public string RenderUC(string path, string id1, string id2)
    {
        Page pageHolder = new Page();
        var viewControl = (ParameterizedTableControl)pageHolder.LoadControl(path);
        viewControl.ID1= id1
        viewControl.ID2 = id2;
        pageHolder.Controls.Add(viewControl);
        StringWriter output = new StringWriter();
        HttpContext.Current.Server.Execute(pageHolder, output, true);

        return output.ToString();
    }

Upvotes: 0

Views: 1191

Answers (2)

Lucas Lopes
Lucas Lopes

Reputation: 86

You can call your function inside your <script> block in the ascx control like this:

<script type="text/javascript">
  function pageLoad(sender, args) {
    alert('haha');
  }
  pageLoad();
</script>

This will make your script run when the browser renders your script tag.

Upvotes: 1

jrummell
jrummell

Reputation: 43077

Any javascript that you want to run once the ajax operation is complete should go in the success handler.

function GetTable() {
    debugger;
    var id_1 = $('#txtID1').val();
    var id_2 = $('#txtID2').val();
    $.ajax({
        url: 'Services/Data.svc/RenderUC',
        data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            debugger;
            $('#divTable').html(data);

            //
            // insert whatever you want here
            //

        },
        error: function showError(xhr, status, exc) {
            debugger;
            alert('error');
        }
    });
}

Upvotes: 1

Related Questions