GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Monday, May 9, 2011

JS -- AJAX

Introduction

AJAX is a mechenisme for communicating with server through background. It enables your client web site to load and sending data from and to server respectively without reloading the page.

Sending Data To Server

Here's a simple example on how to use ajax.

Program Code: Client Side

<input type="text" id="name"/>
<input type="button" value="Send" onclick="sending()"/>

<script>

function sending(){

  var name = document.getElementById('name').value;
  var ajax = new XMLHttpRequest();
  ajax.open("GET", "hello.php?name="+name, false);
  ajax.send();

}

</script>
It's not so complicated. The fisrt, you have the data. The second, you declare an object instance of ajax throught XMLHttpRequest. Then you send your data through ajax. Finish.
And on the server side, you need to write the code to handle it. Here's a code on PHP.

Program Code: hello.php

$name = $_GET['name'];
From the above code, you see that you handling the data as it comes from common request.


Share/Bookmark

Tuesday, March 29, 2011

AJAX - Sample Of Post Method

<table>
<tr><td>Name</td><td>:</td><td><input type="text" id="name"/></td></tr>
<tr><td>City</td><td>:</td><td><input type="text" id="city"/></td></tr>
<tr><td>Age</td><td>:</td><td><select id="age">
    <?php
        $output = '';
        for($i=21; $i<61; $i++){
            $output .= '<option value="'.$i.'">'.$i.'</option>';
        }
        echo $output;
    ?>
    </select></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="button" onclick="Send()" value="Send"/></td></tr>
</table>

<script>
    var lucia = lucia || {};
    lucia.getById = function(id){
        return document.getElementById(id);
    }
    function Send(){
        var name = lucia.getById('name');
        var city = lucia.getById('city');
        var age = lucia.getById('age');
       
        var data = {
            'name': name.value,
            'city' : city.value,
            'age' : age.value
        };
        var json_data = JSON.stringify(data);
       
        var ajax = new XMLHttpRequest();
        ajax.open('POST','hello.php', false);
        ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        ajax.send('data='+json_data);
       
        var response = eval('('+ajax.responseText+')');
       
       
       
       
    }
</script>

Share/Bookmark

Sunday, March 20, 2011

Ajax - TinyMCE Saving

 To get the content of the editor of TinyMCE, use
function save(){
    var mce = tinyMCE.get('content');
    alert(mce.getContent());
}

For initializing the editor, use:
tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Skin options
        skin : "o2k7",
        skin_variant : "silver",       
});

To send the content to the server, use:
function send(){
    var data = tinyMCE.get('content').getContent();
    var ajax = new XMLHttpRequest();
    ajax.open('POST','hello.php',false);
    ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    ajax.send('data='+data);
}

Share/Bookmark

Ajax - Params In Post

To do sending parameter with post, what you need is do a little bit of code:

var ajax = new XMLHttpRequest();
ajax.open('POST', 'hello.php', false);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// below is data you send
ajax.send('name=luna&city=denpasar');

With ajax, you can also get info response from server:
var content_length = ajax.getResponseHeader('Content-length');

Share/Bookmark

Thursday, March 10, 2011

PHP - XML In Sending Data

Here's a code on how to sending data from client to server in the form of xml format. You can see also at this link.
1. file index.php
<h1>Javascript And JSON</h1>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
    Name: <input type="text" id="name"/><br/>
    City: <input type="text" id="city"/><br/>
    Age: <input type="text" id="age"/><br/>
    <input type="button" onclick="sendData()" value="Save"/>
</div>
<div id="response"></div>

Share/Bookmark

JSON Vs XML

Here's a comparison for JSON and XML
1. When you do a request data from server, on the client side you do:
  a. JSON: 
        var data = eval('(' +ajax.responseText+ ')'); or
        var data = null; eval('data ='+ajax.responseText); or
        var data = new Function('return '+ajax.responseText);
  b. XML:
        var data = ajax.reponseXML;

2. On the server side, the process for the request handling is:
  a. JSON:
        $data_json = json_encode($data_array);
  b. XML:
        $data = '<?xml version="1.0"?>';
        header('Content-type: text/xml');
        echo $data;

3. When you do sending data to server, the process in the client is like this one:
  a. JSON:
         var data = {};
         var data_sending = JSON.stringify($data);
  b. XML:
         var xml_data = '<?xml version=\"1.0\"?>';
         var parser = new DOMParser();
         var xmlDoc = parser.parseFromString(xml_data, 'text/xml');

4. And the process on the server is like:
  a. JSON:
         $data = $_GET['data'];
         $data_array = json_decode($data, true);
  b. XML:
         $data = $_GET['data'];
         $xmlDoc = new DOMDocument();
         $xmlDoc->loadXML(data); // or load(file);
         $names = $xmlDoc->getElementsByTagName('name');
         $name = $names->item(0)->nodeValue;

5. Other similarities:
  a. Converting native object to string representations:
     - JSON => JSON.stringify(data);
     - XML => ?????????
  b. Converting string text to native object:
     - JSON => var data = text.parseJSON();
     - XML => var doc = new DOMParser();
              var xmlDoc = doc.parserFromString(data, 'text/xml');


Share/Bookmark

AJAX AND JSON - Sending Data

Here's a demo on how to send data from client to server:
In the client side, the steps are:
1. You get the data using Javascript DOM
2. Then you convert it to Javascript object literal
3. Then you change the object literal to string - JSON.stringify(data)
4. Then you send it through ajax

In the server side:
1. Catch the json data as a like $data = $_POST['data'];
2. Convert the data as an array $data = json_decode($data,true);

The Files:
a. index.php
<h1>Javascript And JSON</h1>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
    Name: <input type="text" id="name"/><br/>
    City: <input type="text" id="city"/><br/>
    Age: <input type="text" id="age"/><br/>
    <input type="button" onclick="sendData()" value="Save"/>

</div>

<script>
function sendData(){
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
   
    var data = {};
    data.name = name.value;
    data.city = city.value;
    data.age = age.value;
   
    var datas = JSON.stringify(data);
   
    var ajax = new XMLHttpRequest();
    ajax.open("GET","hello.php?data="+datas,false);
    ajax.send();
   
    name.value = '';
    city.value = '';
    age.value = '';
   
      
}

</script>

b. hello.php
<?php

$handle = mysql_connect("localhost","root","indonesia");
mysql_select_db("data",$handle);

$data = $_GET['data'];


// convert the json format to php array style
$data = json_decode($data, true);

$query = "INSERT INTO personal_info (name, city, age) VALUES ";
$query .= "('".$data['name']."', '".$data['city']."', 
          ".$data['age'].")";

$result = mysql_query($query);
Share/Bookmark

AJAX And XML

XML can be used as a data format when you handling data transfer between server and client. Here's a code that shows to you on how to use the both:

1. Create File index.php
<h1>Ajax And XML Demos</h1>
<div>Enter a name:
    <input type="text" id="name_id"/>
    <input type="button" onclick="getData()" value="Get Data"/>
</div>

Name: <span id="name"></span><br/>
City: <span id="city"></span><br/>
Age: <span id="age"></span><br/>


<script>
function getData(){
    var name_d = document.getElementById('name_id');
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
   
    var ajax = new XMLHttpRequest();
    ajax.open("GET","hello.php?name="+name_id.value,false);
    ajax.send();
    var data = ajax.responseXML;
   
    name.innerHTML = data.getElementsByTagName('name')[0].childNodes[0].nodeValue;
    city.innerHTML = data.getElementsByTagName('city')[0].childNodes[0].nodeValue;
    age.innerHTML = data.getElementsByTagName('age')[0].childNodes[0].nodeValue;
   
}
</script>


2. Create file: hello.php
<?php
/**
 * Assume the table structure is like this one
 * CREATE TABLE personal_info
 * (id INT NOT NULL AUTO_INCREMENT KEY,
 * name CHAR(20) NOT NULL DEFAULT '',
 * city CHAR(20) NOT NULL DEFAULT '',
 * age INT NOT NULL DEFAULT 0
 * );
 */

$handle = mysql_connect("localhost","root","indonesia");
mysql_select_db("data", $handle);
$name = $_GET['name'];
$name = urldecode($name);

$query = "SELECT * FROM personal_info WHERE name= '$name'";

$result = mysql_query($query);

$output = '<?xml version="1.0" ?>';
$output .= '<data>';
$output .= '<name>'.$name.'</name>';


while($row=mysql_fetch_array($result)){
    $output .= '<age>'.$row['age'].'</age>';
    $output .= '<city>'.$row['city'].'</city>';
}

$output .= '</data>';

header("Content-type: application/xml");
echo $output;

?>
Share/Bookmark

Wednesday, March 9, 2011

JS - AJAX and XML

Here's a demo on how to use xml and ajax as data transport service.
The xml file: data.xml
<?xml version="1.0" ?>
<data>
    <name>Luna Maya</name>
    <city>Denpasar</city>
    <age>27</age>
</data>

The client processing script:
<h1>AJAX and XML</h1>
<div id="name"></div>
<div id="city"></div>
<div id="age"></div>

<script>
function getData(){
    var ajax = new XMLHttpRequest();
    ajax.open("GET","lola.xml",false);
    ajax.send();
    var data = ajax.responseXML;

    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');

    name.innerHTML = data.getElementsByTagName('name')[0].
                     childNodes[0].nodeValue;
    city.innerHTML = data.getElementsByTagName('city')[0].
                     childNodes[0].nodeValue;
    age.innerHTML = data.getElementsByTagName('age')[0].
                    childNodes[0].nodeValue;

}

getData();
</script>
Share/Bookmark

Tuesday, March 8, 2011

JS - Ajax Response As JSON


/**
 * This program is a demos on how to retrieve data using ajax
 * in JSON format. 
 * The process is simple. You create an array in PHP as what the
 * data you want to transfer it to the client. Next, handle the 
 * request using var data = eval('('+ajax.reponseText+')'). 
 * After this one,  you can process the data as object literal
 * in Javascript.
 * Please note, the eval function is the most important!
 * var data = eval('('+ajax.responseText+')');
 * or
 * var data = null;
 * eval("data = "+ajax.responseText);
 * or
 * var data = new Function("return "+ajax.responseText);
 */

1. index.php file
<html>
<head>
<title>JSON Demo</title>

</head>
<body onload="getData(document.getElementById('select').value)">
<h1>JSON Demo</h1>
<select id="select" name="namee" onchange="getData(this.value)">
<option value="luna">Luna</option>
<option value="lady">Lady Gaga</option>
<option value="bill">Bill Clinton</option>
</select>

<p>Name: <span id="name"></span></p>
<p>City:  <span id="city"></span></p>
<p>Age:  <span id="age"></span></p>
<p>Response: <span id="response"></span></p>

<script>
function getData(value){
    var ajax = new XMLHttpRequest();
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
    ajax.open("get","hello.php?namee="+value,false);
    ajax.send();
    var data = eval('('+ajax.responseText+')');
    var response = document.getElementById('response');
    name.innerHTML = data.name;
    city.innerHTML = data.city;
    age.innerHTML = data.age;
}

</script>

</body>
</html>



2. hello.php file
<?php

$namee = $_GET['namee'];
$data = array();

if(strcasecmp($namee,'luna')==0){
    $data = array(
        'name'=>'luna maya',
        'city'=>'denpasar',
        'age'=>27
    );
}else if(strcasecmp($namee,'lady')==0){
    $data = array(
        'name'=>'lady gaga',
        'city'=>'new york',
        'age'=>24
    );
}else if(strcasecmp($namee,'bill')==0){
    $data = array(
        'name'=>'bill clinton',
        'city'=>'virginia',
        'age'=>55
    );
}

echo json_encode($data);

Share/Bookmark