Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Wednesday, October 20, 2010

AjaxFormSubmitter

when you are using AJAX in your web application , you do a lot of cool stuff but some parts of the application is totally boring like creating a form and get every eleement’s value in that form , create a new XMLHttpObject and handle the result.

So i created this class so that you can pass the form id ,  div id , or any html element that has a data you are interested in and send it  asynchronously to a web page , imagine the line of codes and the time that you will save and the most of it cutting the boring time of .

You Can Download The Class From

          http://www.jsclasses.org/package/26-JavaScript-Submit-Form-Data-asynchronously-.html

You need to include JQuery first , because the class is based on JQuery , you can download one from this link

           http://docs.jquery.com/Downloading_jQuery

The Class is  the file called “AjaxFormSubmitter”

To use the class follow this example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
   <meta http-equiv="Content-Type" content"text/html; charset=iso-8859-1">
   <title>Test Ajax Form</title>
   <Script src="jquery-1.3.2.min.js" type="text/javascript"></Script>
   <Script src="AjaxFormSubmitter.js" type="text/javascript"> </Script>
   <script type="text/javascript">
    function OnLoading () {
       alert("I am loading"); 
    }

    function OnSuccess (data){
       alert ("request completed " ); 
       alert(data); 
    }

    function OnError (XML){
       alert(XML);
    }

    function SendData(){
      var AjaxForm = new AjaxFormSubmitter("MyForm"); 
      AjaxForm.SetURL("data.php");
      AjaxForm.SetMethod("POST");
      
      AjaxForm.SetOnSuccess(
           function(data){
              OnSuccess(data);
           }
      );

     AjaxForm.SetOnFailure (
           function (error){
              OnError(error);
           }
     );

     AjaxForm.SetOnLoading (
            function (){
              OnLoading(); 
            }
    ); 

     AjaxForm.Submit(); 
   }  



  </script>
</head>

  <body>
      <form id="MyForm" action="#" method="post" >
          <input type="text" id="name" name="name" value="Text"/> 
          <input type="hidden" id="hidden" name="hidden" value="hiddenVlaue"/>
          <input type="password" id="password" name="password" value="passwordValue"/> <br>
          <input type="checkbox" id="chbox1" name="chbox1"  checked="checked"/> 
          <input type="checkbox" id="chbox2" name="chbox2" />    <br>      
          <input type="radio" id="radio1" name="choice" value="1" />
          <input type="radio" id="radio2" name="choice" value="2"/>
          <input type="radio" id="radio3" name="choice" value="3" checked="checked"/>
          <input type="radio" id="radio4" name="choice" value="4"/><br>
          <select id="Select" multiple="multiple">
              <option value="option1">option one</option>
              <option value="option2">option two</option>
              <option value="option3">option three</option>
          </select> <br>

          <textarea id="textarea">My Text Area</textarea> <br>
          
          <input type="button" value="Send Data" name="Send" onclick="SendData();"/>
      </form>
    </body>
</html>


In The Example you will find a function called “Send Data” , this is the function that do all the work.
var AjaxForm = new AjaxFormSubmitter("MyForm"); 
  AjaxForm.SetURL("data.php");
  AjaxForm.SetMethod("POST");


We created an object from the class  and pass the Form id to the constructor , then we tell the class the url that will receive the data , and the method that will it use “POST or GET”.



the next steps are optional , in case of you are not interested in handling the results.


AjaxForm.SetOnSuccess(
    function(data){
        OnSuccess(data);
    }
);

AjaxForm.SetOnFailure (
     function(error){
        OnError(error);
     }
);

AjaxForm.SetOnLoading (
    function (){
        OnLoading(); 
   }
); 

In the previous screen shot , you tell the class what to do in the following events: success , error , and loading

OnSuccess will recieve the resutned text from the web page , and will be called after the request is completed 

OnFailure Will recieve an object from the XML http Object , and will be called in case that any error happend

OnLoading : will be called before the data is sent .

what you have to do next , is to call the submit function
AjaxForm.Submit();


You have finished , i hope the class will be useful for you
Listed at Hot Scripts Listed in JavaScript





Saturday, August 21, 2010

First AJAX Application

Introduction : What Is AJAX

AJAX is very interesting now a days , and a lot of developers want to know what is AJAX , AJAX stands for "Asynchronous JavaScript And XML" which means it is all about Javascript and XML.
Most of people thought that AJAX is a web programming language like PHP , ASP , .. etc. but it is not , whatever the language you are using for your web application , AJAX is totally independent.
we use AJAX when we need to do something asynchronously and don't make the page flashes. Gmail and Google Earth are a good example of AJAX.

What i need to know before i start working with AJAX ?


  1. a web programming language like PHP , ASP , JSP or whatever you want .
  2. JavaScript , and it is actually not a big deal to specify time to learn JavaScript , if you have a small programming background you can learn JavaScript from tracing others code .
  3. XML , also you won't need anytime for XML , for the simplicity sake XML let you express the data using your own tags
  4. DOM : "Document Object Model" , every element in the HTML Page is actually an object of the document , DOM actually is not a different language , you can think of it as a concept


The First Application : Sign Up Using AJAX the HTML Page < span id="Message"> </span> < from action="#" id="SignUpForm" method="POST"> Username :< input id="Form_Username" type="text" value="" /> Email:<input id="Form_Email" type="text" value=""/> Passwoed:<input id="Form_Password" type="password" value="" /> <input id="SignUpButton" onclick="return SignUp();" type="submit" value="Sign Up" /> <form> The goal of the "span" is to use it for printing the messages related to the sign up process. onClick="return SignUp();" will call the javaScript function - we will create it latter- which is responsible to send the request asynchronously The PHP Page
<?php
// SignUp.php
$UserName = $_REQUEST["Form_Username"];
$Password= $_REQUEST["Form_Password"];
$Email=$_REQUEST["Form_Email"]
$Connect= mysql_connect("localhost","root","password");
mysql_select_db("database");
$SQL = "insert into users 
set 
user_name = '$Username',
user_password= '$Password';                                                  
user_email='$Email'; "
$Query = mysql_query($SQL) 
if( mysql_affected_rows() ==1) 

echo "1"; //user added successfully else

echo "0" // //failed

?>
as you see you have to organize your code in a way that only the intended function will respond and print a text that should be displayed Now The JavaScript Part
function XMLHTTPRequest()
{
var xhr=false;
// if running Internet Explorer
if(window.XMLHttpRequest)
{
try
{
xhr= new XMLHttpRequest();
}
catch (e)
{
xhr= false;
}
}
// if running Mozilla or other browsers
else
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");  
}
catch (e)
{
xhr = false;
}
}
return xhr;
}
function SignUp()
{
var Username=document.getElementById("Form_Username");
var Password=document.getElementById("Form_Password");
var Email=document.getElementById("Form_Email");
var Xml=new XMLHTTPRequest(); 
if (xhr){
var Link=" SignUp.php";
xhr.open("GET",Link,true);
xhr.onreadystatechange = function () { CheckState(xhr);};
xhr.send(null);
}else
return true;
}
function CheckState(xhr)
{
var Message=document.getElementById("Status");
Message.innerHTML="";
if (xhr.readyState == 1)
{
Message.innerHTML="Loading , Please Wait";
}
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
if(hr.responseText=="1")
Message.innerHTML="User Added";
}
else
{
Message.innerHTML="Error occurred";
}
}
}