Skip navigation


Baru bikin wrapper yang lumayan enak buat digunain.

/*AJAX Wrapper!*/
/**
 * @param method Request method
 * @param url Request URL
 * @param onLoad Function callback on request complete
 * @param onProgress Function callback on request progress
 * @param data
 */
function doRequest(method,url,async,onLoad,onProgress,data) {
    var xhr;
    try{
        xhr=new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try{
            xhr=new ActiveXObject("Msxml2.xhr");
        } catch (e) {
            try {
                xhr=new ActiveXObject("Microsoft.xhr");
            } catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    // W3C requests and streaming
    xhr.open(method,url,async);
    if (method == "POST") /* Set request header on POST */
    {
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Content-length", data.length);
        xhr.setRequestHeader("Connection", "close");
    }
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 3) // interactive mode
            onProgress(xhr.responseText);
        if (xhr.readyState == 4) // finished
            onLoad(xhr.responseText,xhr.status);
    }
    xhr.send(data); // finally send the request whether it be XDR or XHR
}


Untuk contoh penggunaannya, berikut akan dipakai login sederhana menggunakan AJAX.

function login()
{
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var data = "username="+username+"&"+"password="+password;
    doRequest(
        "POST",
        "ajax1.php",
        true,
        function (responseText)
        {
            alert("Response : " + responseText);
        },
        function (responseText)
		{

		},
        data
        );
}

Contoh backendnya

<?php
	if ($_POST&#91;'username'&#93; == 'petra' && $_POST&#91;'password'&#93; == 'password')
		echo 'true';
	else
		echo 'false';
?>

Kode penuhnya bisa diambil di sini. (as usual, rename extension to zip)

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: