WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : ezRemoteScripter - A little remote scripting (AJAX) helper
Categories : PHP, Java Script, AJAX Click here to Update Your Picture
Khair-ed Din Husseini
Date : Dec 26th 2005
Grade : 2 of 5 (graded 6 times)
Viewed : 9986
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Khair-ed Din Husseini
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

A couple of days ago I was browsing the net for some remote scripting (also known as AJAX) examples and how to use the XmlHttpRequest object. However, all examples were quite nasty in imiplementation so I decided to write an nice little javascript wrapper around the XmlHttpRequest object.

// JavaScript Document
function EzRemoteScripter() {
    //private variables
    var _XmlHttpRequest = null;
    var _This = null;
   
    //public properties
    this.GetResponseXML = function() {
        return (_XmlHttpRequest) ? _XmlHttpRequest.responseXML : null;
    }
   
    this.GetResponseText = function() {
        return (_XmlHttpRequest) ? _XmlHttpRequest.responseText : null;
    }
   
    this.GetXMLHttpRequestObj = function() {
        return _XmlHttpRequest;
    }
   
    //public methods
    this.InitXmlHttpRequest = function(Method, CallUri) {
        _InitXmlHttpRequest();
        _This = this;
        switch( arguments.length ) {
            case 2:
                _XmlHttpRequest.open(Method, CallUri);   
                break;
            case 3:
                _XmlHttpRequest.open(Method, CallUri, arguments[2]);
                break;
        }
       
        if( arguments.length >= 4) {
            _XmlHttpRequest.open(Method, CallUri, arguments[2], arguments[3]);
        }
    }
   
    this.Commit = function(Data) {
        if( _XmlHttpRequest ) {
            _XmlHttpRequest.send(Data);
        }
    }
   
    this.Close    = function() {
        if( _XmlHttpRequest ) {
            _XmlHttpRequest.abort();
        }
    }
   
    //public events
    this.OnUninit         = function() {};
    this.OnLoading         = function() {};
    this.OnLoaded         = function() {};
    this.OnInteractive     = function() {};
    this.OnSuccess        = function() {};
    this.OnFailure         = function() {};
   
    //private events
    function _OnUninit()         { _This.OnUninit(); };
    function _OnLoading()         { _This.OnLoading(); };
    function _OnLoaded()         { _This.OnLoaded(); };
    function _OnInteractive()     { _This.OnInteractive(); };
    function _OnSuccess()         { _This.OnSuccess(); };
    function _OnFailure()         { _This.OnFailure(); };
   
    //private methods
    function _InitXmlHttpRequest() {
        _XmlHttpRequest = _GetXmlHttpRequest();
        _XmlHttpRequest.onreadystatechange = _StateHandler;
    }
   
    function _StateHandler() {
        switch(_XmlHttpRequest.readyState) {
            case 0:
                window.setTimeout("void(0)", 100);
                _OnUninit();
                break;
            case 1:
                window.setTimeout("void(0)", 100);
                _OnLoading();
                break;
            case 2:
                window.setTimeout("void(0)", 100);
                _OnLoaded();
                break;
            case 3:
                window.setTimeout("void(0)", 100);
                _OnInteractive();
                break;
            case 4:
                if (_XmlHttpRequest.status == 200) {
                    _OnSuccess();
                } else {
                    _OnFailure();
                }
                return;
                break;
        }
    }
   
    function _GetXmlHttpRequest() {
        var requester
        try {
            requester = new XMLHttpRequest();
        } catch (error) {
            try {
                requester = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (error) {
                return null;
            }
        }
        return requester;
    }
}



The code is quiet selfexplanatory. However i have here also an exmaple of the usage. It is very simple.

Here is first the html (yes html file) that will show us our little example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>
        <script language="javascript" type="text/javascript" src="NIS.RemoteScripter.js"></script>
        <script language="javascript" type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <div id="DataContainer"></div>
        <button type="button" onclick="Go(test)">test</button>
    </body>
</html>


and here out php script that will supply us with data:

<?php
header
("Content-type: text/xml");
echo
"<books><book>h123o</book><book>hello2</book><book>asdddo3</book></books>";
?>


Note the usage of the header. It is very important to identify the data as xml so that the XmlHttpRequest object can use the data in order to be manipulated with the standart DOM methods.


Just create a new javascript file with the name test.js (or whatever you want to) and write following:

// JavaScript Document
////////////////////////////////////////////////////////////
var test = new EzRemoteScripter();
var div = window.document.getElementById("DataContainer");

//this function is used to find our div element that will
//show all data that is being returned by our wrapper.
function SetDiv() {
    if( ! div) {
        div = window.document.getElementById("DataContainer");
    }
}

////////////////////////////////////////////////////////////
//here we set the OnUninit event with a function.
//this event is fired if the XmlHttpRequest object was not
//initialized when we call the remote php script.
test.OnUninit         = function() {
    SetDiv();
    div.innerHTML = "Uninitialized!!";
}
////////////////////////////////////////////////////////////   
//This event is firing while data is being received from our remote script. Notice that when using document.getElement[..] you have to make sure that the element is set to our variable div.
test.OnLoading         = function() {
    SetDiv();
    div.innerHTML = "Loading...";
}
////////////////////////////////////////////////////////////   
//Event is fired when data finished loading
test.OnLoaded         = function() {
    SetDiv();
    div.innerHTML = "Loaded...";
}
////////////////////////////////////////////////////////////
//now this event is kinda tricky. Now when finished loading all data resides in the XmlHttpRequest object.
//however when getting the data from the XmlHttpRequest object the OnInteractive event is fired. That means it is the data transfer between the XmlHttpRequest object and your script.
test.OnInteractive     = function() {
    SetDiv();
    div.innerHTML = "Interacting...";
}
////////////////////////////////////////////////////////////
//this event is the most used and most important event.
//it is fired if the data has been loaded with a success.
//
test.OnSuccess        = function() {
    SetDiv();
    div.innerHTML = "";
        // here we are getting the data from the XmlHttpRequest object (OnInteractive is being fired)
        //alternatively you may get the data as a string using the test.GetResponseText()
    var obj = test.GetResponseXML();
    var books = obj.getElementsByTagName("book");
    for(var i=0; i < books.length; i++) {
        var myLI = document.createElement("LI");
        myLI.innerHTML = books[i].firstChild.data;
        div.appendChild(myLI);
    }
}
////////////////////////////////////////////////////////////
test.OnFailure         = function() {
    SetDiv();
    div.innerHTML = "Failed!";
}
////////////////////////////////////////////////////////////
//this is the funciton that actually calls out php script to get the xml data. pretty easy to use.
//However, you HAVE to init and commit on each call otherwise the script won't work. you may also use the POST method to tranfer data instead of get. To do this you would have to do following:
//d.InitXmlHttpRequest("POST", "test.php");
//d.Commit("myVar=hello&mySecondVar=world");
//
//if you don't want to send any data just pass null to the Commit method. If you leave it empty FireFox will complain.
function Go(d) {
    d.InitXmlHttpRequest("GET", "test.php");
    d.Commit(null);
}
////////////////////////////////////////////////////////////



Now happy remote scripting :)
Zephyr: AJAX Based Framework for PHP5 Developers
Categories : PHP, AJAX, Frameworks, Java Script, Web Applications
Remote Scripting: send form POST data to a script and insert the results into a page without refreshing the page.
Categories : PHP, AJAX, HTML and PHP, Java Script
The Ajax Tree view class fetches data from a db for the requested parent category id. The data is then stored in an array and converted into JSON (Javascript Object Notation) format. This format is then used by JavaScript for populating tree view.
Categories : PHP, PHP Classes, Java Script, AJAX, Databases



Ajax-based dictionary
Categories : PHP, Java Script, AJAX
Classic guest book made with PHP and Flash
Categories : PHP, Flash, Java Script
Ajax - Perform a simple server side request and update the current HTML page.
Categories : AJAX, Java Script, Beginner Guides
filesystem Show Files Script
Categories : PHP, Filesystem, Java Script
Menu in sliding bar or tree style. Handles frames by using small amount of javascript. Handles external and internal pages. Allows custom code to replace a menu item.
Categories : PHP Classes, PHP, Java Script, DHTML
PHP Calendar
Categories : PHP, Calendar, Date Time, Java Script, CSS
php Free chat simple fast and customizable chat server that uses a simple filesystem for message and nickname storage
Categories : PHP, AJAX, XML, Complete Programs
[PHP5] NOTIMEOUT PACKAGE
Categories : PHP, PHP Classes, AJAX
A Complete table(ADD,EDIT,VIEW,DELETE) management System PHP,MYSQL, JAVASCRIPT
Categories : PHP, MySQL, Java Script, Databases
A Simple sign up script with PHP and JavaScript validations.
Categories : PHP, Java Script, MySQL, Databases
Protect your mailto: email addresses from bots
Categories : PHP, Email, Java Script
 Brian Tafoya wrote :1670
One minor problem... when using the post method the content type and length much be passed.

Change the InitXmlHttpRequest method to the below...

    //public methods
    this.InitXmlHttpRequest = function(Method, CallUri) {
        _InitXmlHttpRequest();
        _This = this;
        switch( arguments.length ) {
            case 2:
                _XmlHttpRequest.open(Method, CallUri);   
                break;
            case 3:
                _XmlHttpRequest.open(Method, CallUri, arguments[2]);
                break;
        }
       
        if( arguments.length &gt;= 4) {
            _XmlHttpRequest.open(Method, CallUri, arguments[2], arguments[3]);
        }
        
        if(Method == `POST`) {
            _XmlHttpRequest.setRequestHeader(`Content-Type`, `application/x-www-form-urlencoded`)
            _XmlHttpRequest.setRequestHeader(`Content-length`, `0`);
        }
    }