Novak
Novak

Reputation: 2768

The use of JS functions to call Ajax, with ASP.NET controls

I am coming from a PHP background, so I'm used to having a PHP file to handle all my ajax calls.

Lately I was introduced to the ASP.NET controls, and the environment in general.

I wonder, what is the correct way to handle ajax requests, when they are supposed to be called from a JavaScript file?

Also, if you have a better option than AJAX (with ASP.NET), I would like to see a small implementation of yours, using it, if possible.

Thanks! Guy

Upvotes: 0

Views: 244

Answers (1)

lem2802
lem2802

Reputation: 1162

I have seen a lot of ajax implentations for ASP.NET... but i think the best of all them is my own... :D

just make a javascript function like this:

<script type="text/javascript">
    function callasync(url, id_contenedor) {
        var ajax = false;

        if (window.XMLHttpRequest) {
            //Mozilla, Safari, etc 
            ajax = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            //IE       
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                //Versión antigua    
                try {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                }
            }
        }
        else
            return false;

        if (id_contenedor != '') {
            document.getElementById(id_contenedor).innerHTML = "<table width='100%' height='100%'><tr><td style='text-align: center; vertical-align: center;'><a class='LabelInfo'>Whait...</a><br /><img src='Imagenes/Esperar.gif' /></td></tr></table>";
        }

        ajax.onreadystatechange = function () {
            pageload(ajax, id_contenedor);
        }

        ajax.open('GET', url, true);
        ajax.send(null);
    }

    function pageload(ajax, id_contenedor) {
        if (ajax.readyState == 4 && (ajax.status == 200 || window.location.href.indexOf("http") == -1))
            if (id_contenedor != '') {
                document.getElementById(id_contenedor).innerHTML = ajax.responseText;
                ResizeCanvas();
            }
    }
</script>

Then call the function "callasync" with a url and div's ID...

callasync('mypage.aspx?QS_KEY=123', 'divId');

In the ASP.NET codebehind... Override the Render method like this:

protected override void Render(HtmlTextWriter writer)
{
    if (Request.QueryString["QS_KEY"] != null)
    {
        //render what you want.
    }
    else
    {
        base.Render(writer);
    }
}

Upvotes: 1

Related Questions