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

What is Ajax Request?

Some PHP programmers would argue that the most important use of JavaScript is to provide
Ajax functionality to your programs. Whether or not you agree, Ajax is certainly a central
part of today’s Internet. Standing for Asynchronous JavaScript and XML, Ajax is really a
misnomer because it often has little to do with XML as it can handle all manner of file types.
However, when Microsoft first introduced the feature in Internet Explorer 5 (back in 1999),
they named the new ActiveX object XMLHttpRequest, and the name has stuck ever since.
This plug-in is the pure JavaScript side of the Ajax equation, which requires two
programs, one on the client computer and one on the server, to interact with each other.

This and the next two plug-ins in this chapter are comprised entirely of JavaScript code,
rather than the amalgam of JavaScript and PHP used by the rest of the plug-ins.
The plug-in is a little more complicated than it ought to be due to the different methods
various browser creators have chosen to implement Ajax. For example, although Microsoft
came up with the XMLHttpRequestobject in Internet Explorer 5, it then decided to use an
entirely different approach for IE6. And then other browser developers chose yet another
away of doing things.

function PIPHP_JS_AjaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}

This means that there are three types of Ajax methods to take into account, according to
which browser is in use. Thankfully, there’s an easy way to apply these in turn without
creating errors, and that’s to use JavaScript’s try… catchsyntax. With it you can try a
command using a trystatement, and if it fails, program execution will continue at the
matching catchstatement. Furthermore, you can nest these inside each other, so you can
place another trystatement inside a catchstatement.
This is exactly the technique employed in this plug-in, except that I choose to test for
non-Microsoft browsers first by assigning the variable requestthe object returned by
calling up a new XMLHttpRequest()object. This will usually succeed on Firefox, Chrome,
Safari, and Opera (as well as other browsers), but will fail on all versions of Internet
Explorer. If this happens, an attempt is then made to assign requestthe value returned
from creating the new ActiveX object Msxml2.XMLHTTPby attempting to use the command
new ActiveXObject()with that argument.

Post Ajax Request

The previous plug-in provides a means of creating an XMLHttpRequestobject, with which
this plug-in makes a POSTrequest to the server to request some data to be transferred back
to the browser. Both of these requests happen seamlessly in the background with the user
generally unaware that such things are taking place. A POSTrequest is where data is sent to
the server within header messages, rather than as part of a URL tail or query string, as is
the case with GETrequests.

function PIPHP_JS_PostAjaxRequest(url, params, target)
{
request = new PIPHP_JS_AjaxRequest()
request.onreadystatechange = function()
{
if (this.readyState == 4)
if (this.status == 200)
if (this.responseText != null)
target.innerHTML = this.responseText
// You can remove these two alerts after debugging
else alert("Ajax error: No data received")
else alert( "Ajax error: " + this.statusText)
}
request.open("POST", url, true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.setRequestHeader("Content-length",
params.length)
request.setRequestHeader("Connection", "close")
request.send(params)
}
function PIPHP_JS_AjaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
</script>

Note that the entire Facebook page is being loaded into the <div>, in the same way as if
you had included it within an <iframe>element. This is purely an example of how to
incorporate such a page, and you do not gain access to the Facebook API using this method.
Instead a surfer using such an embedded page to log in will be directed straight to the
Facebook servers for the remainder of the process.
To try this example for yourself, type it in and save it as ajaxpost.html. You can also
download it from the Download link at www.pluginphp.com. After extracting the file plug-ins.
zip, you will find the example in the location 11/ajaxpost.html.
However, don’t run the file until you also have the PHP part of the equation on the server.
It’s not a large program but it’s very important because it’s the part of the process that receives
requests from the browser and responds to them. In this case, it returns a requested web page:
<?php // ajaxpost.php
if (isset($_POST['url'])) echo file_get_contents($_POST['url']);
?>
What this program does is check whether the variable urlhas been posted to it.

Validate Email address

 

Checking Email 


Web sites often use email addresses as usernames because they are guaranteed to be unique, as long as they are valid. In addition, the organizations can use the email addresses to communicate with their users later. You do not have to initiate a server round trip just to validate an email address, however. This task can be initiated in the client, which cancels the submission of the username to the server if the email syntax is invalid.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head> <script type="text/javascript" src="js/http_request.js"></script> 
<script type="text/javascript" src="js/email.js"></script>
 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>Enter email</title>
 </head> <body> 
<form action="javascript:void%200">
 <div id="message"></div>
 Enter email: <input type="text" name="email" size="25"> 
<br /> <button type="submit" name="submit" value="Send">Send</button>
 </form> </body> </html>



This function creates a new Email object, validates the user's email address,
 and, if it's valid, submits it to a server component.
Let's take a closer look at the checkAddress( ) function:
function checkAddress(val){
    var eml = new Email(val);
    var url;
    eml.validate(  );
    if (! eml.valid) {eMsg(eml.message,"red")};
    if(eml.valid)
    {
        url="http://www.parkerriver.com/s/checker?email="+
            encodeURIComponent(val);
        httpRequest("GET",url,true,handleResponse);
    }
}



var user,domain, regex, _match;

window.onload=function(  ){
    document.forms[0].onsubmit=function(  ) {
        checkAddress(this.email.value);
        return false;
    };
};
/* Define an Email constructor */
function Email(e){
    this.emailAddr=e;
    this.message="";
    this.valid=false;
}

function validate(  ){
    //do a basic check for null, zero-length string, ".", "@",
    //and the absence of spaces
    if (this.emailAddr == null || this.emailAddr.length == 0 ||
    this.emailAddr.indexOf(".") == -1 ||
    this.emailAddr.indexOf("@") == -1 ||
    this.emailAddr.indexOf(" ") != -1){
    this.message="Make sure the email address does " +
    "not contain any spaces "+
    "and is otherwise valid (e.g., contains the \\"commercial at\\" @ sign).";
        this.valid=false;
        return;
    }

    /* The local part cannot begin or end with a "."
    Regular expression specifies: the group of characters before the @    
    symbol must be made up of at least two word characters, followed by zero   
    or one period char, followed by at least 2 word characters. */
    regex=/(^\\w{2,}\\.?\\w{2,})@/;
    _match = regex.exec(this.emailAddr);

    if ( _match){
        user=RegExp.$1;
        //alert("user: "+user);
    } else {
       this.message="Make sure the user name is more than two characters, "+
            "does not begin or end with a period (.), or is not otherwise "+
            "invalid!";
        this.valid=false;
        return;
    }
    //get the domain after the @ char
    //first take care of domain literals like @[19.25.0.1], however rare
    regex=/@(\\[\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}.\\d{1,3}\\])$/;
    _match = regex.exec(this.emailAddr);

    if( _match){
        domain=RegExp.$1;
        this.valid=true;
    } else {
/* The @ character followed by at least two chars that are not a period (.),
followed by a period, followed by zero or one instances of two or more
characters ending with a period, followed by two-three chars that are 
not periods */
        regex=/@(\\w{2,}\\.(\\w{2,}\\.)?[a-zA-Z]{2,3})$/;
        _match = regex.exec(this.emailAddr);
        if( _match){
            domain=RegExp.$1;
           //alert("domain: "+domain);
        } else {
            this.message="The domain portion of the email had less than 2 
                         chars "+
                         "or was otherwise invalid!";
            this.valid=false;
            return;
        }
    }//end domain check
    this.valid=true;

}

//make validate(  ) an instance method of the Email object
Email.prototype.validate=validate;

function eMsg(msg,sColor){
    var div = document.getElementById("message");
    div.style.color=sColor;
    div.style.fontSize="0.9em";
    //remove old messages
    if(div.hasChildNodes(  )){
        div.removeChild(div.firstChild);
    }
    div.appendChild(document.createTextNode(msg));

}
//a pull-it-all-together function
function checkAddress(val){
    var eml = new Email(val);
    var url;
    eml.validate(  );
    if (! eml.valid) {eMsg(eml.message,"red")};
    if(eml.valid)
    {
        //www.parkerriver.com
        url="http://www.parkerriver.com/s/checker?email="+
            encodeURIComponent(val);
        httpRequest("GET",url,true,handleResponse);
    }
}
//event handler for XMLHttpRequest
//see Hack #24
function handleResponse(  ){
    //snipped...
}

First, the code sets up the handling for the user's click on the Send button. window.onload specifies an event handler that is called when the browser completes the loading of the web page:
window.onload=function(  ){
    document.forms[0].onsubmit=function(  ) {
        checkAddress(this.email.value);
        return false;
    };
};

Validate a Text Field


No web developers want their Ajax applications to hit the network with requests if the users leave necessary text fields blank. Thus, checking that input elements of type text and the large boxes called textareas in HTML contain values is one of the most common forms of validation.
This hack shows the code for checking if a text control is blank. The inline way of doing this is by assigning a check for the field's value in the text field's event handler:
 
<input type="text" name="firstname" id="tfield" onblur=
"if (this.value) {doSomething(  );}" />

or in the textarea's event handler:
<textarea name="tarea" rows="20" id="question" cols="20" onblur=
"if (this.value) {doSomething(  );}">

The JavaScript phrase if (this.value) {...} returns false if the user leaves a field blank, so the function call doSomething( ) will never occur. JavaScript evaluates a blank web-form text field as the empty string or "", which evaluates to false when it's used in the context of a programming test. The this keyword is a nice generic way of referring to the form field that contains the event handler attribute.

Probably a better way of going about your event-handling tasks is to separate the logic of your code from the HTML or template text that comprises the application's visual aspects. The JavaScript goes into an external file that the HTML page imports with a script tag. Inside the external file, the code binds a field's various event handlers to a function or the code that represents your application's behavior.
Let's take the following web page, myapp.html, which includes the following HTML in its header:
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="js/hacks_method.js"></script>
    <title>Cool Ajax application</title>
</head>

The file hacks_method.js is located in a directory js, which is in the same directory as the HTML file. The HTML file contains the same textarea and text field as mentioned earlier, except these fields no longer have an onblur attribute. The JavaScript file includes this code:
 
window.onload=function(  ){
    var txtA = document.getElementById("tarea");
    if(txtA != null){
        txtA.onblur=function(  ){
            if (this.value) { doSomething(  );}
        };
    }
    var tfd = document.getElementById("tfield");
    /* An alternative:
    if(tfd != null && txtA != null){tfd.onblur = txtA.onblur; }
    */
    if(tfd != null){
        tfd.onblur=function(  ){
            if (this.value) { doSomething(  );}
        };
    }
}

window.onload involves the binding of the load event to your blank-field checks. load occurs when the browser has completed loading the web page, so when that happens, all the stuff after window.onload= follows.
The getElementById( ) method returns a reference to an HTML element

Ajax code

 
The keystone of AJAX is the XMLHttpRequest object.
Different browsers use different methods to create the XMLHttpRequest object.
Internet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript object called XMLHttpRequest.
 
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
  {
  var xmlHttp;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return false;
        }
      }
    }
  }
</script>
<form name="myForm">
Name: <input type="text" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>
 
Example explained: First create a variable xmlHttp to hold the XMLHttpRequest object.
Then try to create the object with XMLHttp=new XMLHttpRequest(). This is for the Firefox, Opera, and Safari browsers. If that fails, try xmlHttp=new ActiveXObject("Msxml2.XMLHTTP") which is for Internet Explorer 6.0+, if that also fails, try xmlHttp=new ActiveXObject("Microsoft.XMLHTTP") which is for Internet Explorer 5.5+
If none of the three methods work, the user has a very outdated browser, and he or she will get an alert stating that the browser doesn't support AJAX.
Note: The browser-specific code above is long and quite complex. However, this is the code you can use every time you need to create an XMLHttpRequest object, so you can just copy and paste it whenever you need it. The code above is compatible with all the popular browsers: Internet Explorer, Opera, Firefox, and Safari.
The next chapter shows how to use the XMLHttpRequest object to communicate with the server.
 

AJAX is Based on Web Standards


AJAX stands for Asynchronous JavaScript And XML.
AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).
AJAX is not a new programming language, but a new way to use existing standards.
With AJAX you can create better, faster, and more user-friendly web applications.
AJAX is based on JavaScript and HTTP requests.

Asynchronous JavaScript and XML

AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications.


With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer HTTP requests between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
The AJAX technique makes Internet applications smaller, faster and more user-friendly.

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object
With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

XMLHttpRequest-Ajax

To do this, you must understand the three ways of creating an XMLHttpRequest object
• IE 5: request = new ActiveXObject("Microsoft.XMLHTTP")
• IE 6+: request = new ActiveXObject("Msxml2.XMLHTTP")
• All others: request = new XMLHttpRequest()
This is the case because Microsoft chose to implement a change with the release of
Internet Explorer.



The readyState property
Now we get to the nitty-gritty of an Ajax call, which all hangs on the readyState property.
The “asynchronous” aspect of Ajax allows the browser to keep accepting user
input and changing the screen, while our program sets the onreadystatechange property
to call a function of our choice each time readyState changes. In this case, a nameless
(or anonymous) inline function has been used, as opposed to a separate, named function.
This type of function is known as a callback function, as it is called back each time
readyState changes

request.onreadystatechange = function()
{
if (this.readyState == 4)
{
// do something
}
}

Testing Ajax Event Handlers using Jasmine Spies

JavaScript has several methods that execute asynchronously, such as setTimeout(), Ajax calls, as well as event-driven processes. These examples all have to wait until the current execution thread comes to an end and surrenders to the next event, making asynchronous processes hard to test. Fortunately, the Jasmine JS testing library comes equipped with a couple of tools for handling callbacks.

magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public


What is CURL?

CURL stands for Client URL Library.

CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

What is triggers?

A trigger is a database object which is associated with particular database table.
Triggers gets called automatically when particular event(INSERT, UPDATE, DELETE)
occurs on table.

What is LAMP?

LAMP means combination of Linux, Apache, MySQL and PHP.

How get the value of current session id?

Session_id() returns the session id for the current session.

How register the variables into a session?

session_register ($session_var) function.

What are the different tables present in mysql?

Total 5 types of tables we can create

1. MyISAM

2. Heap

3. Merge

4. InnoDB

5. ISAM

6. BDB

MyISAM is the default storage engine

Load from the Server-Ajax

The first is to keep the templates remote and use an XMLHttpRequest object to retrieve
additional markup. This approach is more convenient for single-page applications than
for multiple-page applications.

Ajax Animations

An animated PNG image is only one of the embellishments you see in web applications
today. Most animations are created by manipulating elements on a page. Part
of developing an application on the Web with Ajax is making it a Web 2.0 application.

magic_quotes_gpc, magic_quotes_runtime

Magic quotes is the name of a PHP feature that automatically quotes input
data, by using the addslashes() function. Historically, this was used so that
form data could be used directly in SQL queries without any security or quoting
issues. Today, form data is used for much more, and magic quotes quickly
get in the way. We recommend that you disable this feature, but portable code
must be aware of these settings and deal with them appropriately by calling
stripslashes() on GPS (GET, POST, and cookie) data.

Associative Arrays?

You can use string values as keys. For example, you might create an array
like this:

$myStuff = array();
$myStuff[“name”] = “andy”;
$myStuff[“email”] = “andy@fsdsd.ca”;
Print $myStuff[“name”];

Associative arrays are different than normal (numeric-indexed) arrays in
some subtle but important ways:
The order is undefined. Regular arrays are always sorted based on the
numeric index. You don’t know what order an associative array will be
because the keys aren’t numeric.

 You must specify a key. If you’re building a numeric-indexed array, PHP
can always guess what key should be next. This isn’t possible with an
associative array.

 Associative arrays are best for name-value pairs. Associative arrays are
used when you want to work with data that comes in name/value pairs.
This comes up a lot in PHP and XHTML. XHTML attributes are often in
this format, as are CSS rules and form input elements.

✦ Some of PHP’s most important values are associative arrays. The $_
REQUEST variable (described in Chapter 3 of this minibook) is an important
associative array. So are $_GET, $_POST, and several others.

Make sure to include quotation marks if you’re using a string as an array
index.

$_GET , $_POST,$_COOKIE??

$_GET contains any variables provided to a script through the GET method.
 $_POST contains any variables provided to a script through the POST method.
 $_COOKIE contains any variables provided to a script through a cookie.

What line should you add to the Apache configuration file to ensure that the .php extension is recognized?

This line ensures that Apache will treat files ending with the .php extension as
PHP scripts:
AddType application/x-httpd-php .php