Information Computer

Tuesday, August 2, 2011

Ajax Javascript

May still be many who do not know what it was ajax. I think ajax is a web-based programming techniques used to create an interactive web application. Ajax is a combination of server side scripting and client side scripting. so ajax is some combination of Web programming such as javascript, PHP, DOM, HTML, and others.

ajax point will update the contents of a web without reloading process. ajax will do so working in an asynchronous data exchange. please note the exchange of data has 2 post and get methods. ajax script this time using two methods. The following examples use the ajax script.

if you try this script at home. Your computer must be installed xampp as a stand-alone server (localhost).

script file index.php

<html>
<head>
<script src=ajax.js></script>
</head>
<body>
<input type=text id=nama >
<input type=submit onclick=kirim("POST") value=POST>
<input type=submit onclick=kirim("GET") value=GET><br>
<div id=hasil />
<body>
</html>

script file ajax.js

var ajax;
if(window.ActiveXObject){
    ajax = new ActiveXObject("MicrosoftXMLHTTP");
}else {
    ajax = new XMLHttpRequest();
}

function proses(metode,url,params,id,output) {
    if (metode == 'POST'){
        ajax.open("POST",url,true);
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    }else{
        ajax.open("GET",url+'?'+params,true);
        params = null ;
    }
    ajax.onreadystatechange = function Response(){
        respon =  ajax.responseText;
        obj = document.getElementById(id) ;
        switch(output){
            case 'innerHTML' : obj.innerHTML = respon;
                break ;
        }
    }
    ajax.send(params);
}

function kirim(metode){
    id = "hasil" ;
    output = 'innerHTML' ;
    nama = document.getElementById('nama').value ;
    url = "ajax.php";
    var params = "nama="+escape(nama);

    proses(metode,url,params,id,output);
}

script file ajax.php

<?php
    if(isset($_POST['nama'])){
        $text1 = $_POST['nama'];
        echo $text1." <i>metode post</i>" ;
    }else if(isset($_GET['nama'])){
        $text2 = $_GET['nama'];
        echo $text2." <i>metode get</i>" ;
    }else{
        echo "null";
    }
?>

create a third file, and be simple ajax. thank :)

Related Posts



Followers