AJAX

12K

Solutions

13

Articles & Videos

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.

Share tech news, updates, or what's on your mind.

Sign up to Post

Article Header
This article discusses how to implement server side field validation and display customized error messages to the client.
4
Free Tool: IP Lookup
LVL 8
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to use "screen scrapers" to attack web forms.
4
 
LVL 1

Expert Comment

by:Braveheartli
Comment Utility
it's a great article. I wish I had read it earlier.
Thank you very much Ray Paseur
0
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX.

The logical flow for the problem should be:
  1. Write an event handler for the first drop down box to get the user's selections.
  2. Send the user input to the server
  3. At the server, retrieve the data from the client side and process it; then send the result to client side.
  4. At the client, use Javascript to parse the server response and update the other drop down box.


Write an event handler for the first drop down box to get the user's selections:

It sounds difficult. What is an "event handler"?  In fact, every user action performed on the web page triggers an event. To handle those events, we need to write a Javascript function, and we call these javascript functions "event handlers". To handle the user's selection of an item in drop-down box, we need to capture the onchange event. Here is a sample code:
 
 <select id=type name="type" onchange="updateData(this)">

Open in new window


The above code means that a function named "updateData" would be triggered when user selects an item from this drop down box. Here the variable "this" means the dropdown box itself. Let's see what happens in the "updateData" function:
function updateData(dropDownBox)
{
  var value=dropDownBox.options[dropDownBox.selectedIndex].value;
  if (value!="") //Ensure no empty value is submitted to server side
  {
    jQuery.post("getResult.php","type="+value,updateNumber);
  }
}

Open in new window


Send the user input to the server

The statement:

var value=dropDownBox.options[dropDownBox.selectedIndex].value;

Open in new window

retrieves user input from the first drop down box. The following statement mean user input is sent to server side php script "getResult.php".
 
jQuery.post("getResult.php","type="+value,updateNumber);

Open in new window

1

Introduction

A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer is "You can't." This is a restriction of the HTTP client / server protocol. The only time the server can send information to the client is in response to a request.  So it follows that we need a way for the client to request a progress report and a way for the server to send the progress report.  This article sets up the two parts of the application and builds them step-by-step so you can see exactly how this can be done.  We use jQuery and AJAX in a way that allows the client script to call the server-side script and to get back an indicator of progress.


The Visual Effect in the Browser

When we first load the client web page, we will have an area reserved for the progress bar.  As progress occurs (as indicated by the signal from the server) our progress bar will become visible and move across from left to right until the process is completed.  At the end, it will say "All Done" then it will fade from view and collapse out of the web page.  Here are screen-capture examples of the visual effects.  We used very bright colors for this example; your choice of size and color would be made with your design goals in mind.  These are settable via CSS.


Before the process starts:

jquery-progress-bar-1.pngAfter the progress bar appears:

jquery-progress-bar-2.pngAs the progress bar continues to show greater and greater progress:

jquery-progress-bar-3.pngWhen the progress indicator exceeds 99%:

jquery-progress-bar-4.pngAfter "All Done!" the progress bar fades out and disappears from the page:

jquery-progress-bar-5.png

The Server-Side Script

First we will build a simulation of the server side of the two-part application.  The server will sense the progress of our long-running job and will return a single value to the client - an integer, representing the percentage of completion.  In order to simulate the progress, we will use a simple counter which we will keep in the PHP session.  By storing the counter in the session, we can add to it on each request to the server-side script, creating the same effect we might see if the server-side script were taking an actual measurement of our progress toward a goal.  Have a look at line 15.  It's only there to simulate some kind of variation in the reported progress.  In real life, this "counting" scenario would be replaced by some programmatic method of determining the percentage of progress toward our goal.  The determination, however it is made, would be set into a positive integer of range 1-99 which is echo'ed to the browser output stream (and therefore returned to the client-side jQuery script that called our progress monitor).

<?php // demo/jquery_progress_bar_server.php
                                        error_reporting(E_ALL);
                                        
                                        // SESSION ALLOWS US TO HAVE STATIC VARIABLES
                                        session_start();
                                        
                                        // IF THIS IS THE FIRST STEP, SET THE PROGRESS BAR TO ZERO
                                        if (empty($_SESSION['progress']))
                                        {
                                            $_SESSION['progress'] = 0;
                                        }
                                        
                                        // INCREMENT THE PROGRESS COUNTER
                                        $advance = 10;
                                        $advance = rand(5,10);
                                        $_SESSION['progress'] += $advance;
                                        
                                        
                                        // IF THIS IS THE LAST STEP, ELIMINATE THE SESSION VARIABLE
                                        if ($_SESSION['progress'] > 99)
                                        {
                                            unset($_SESSION['progress']);
                                            session_write_close();
                                            die('100');
                                        }
                                        
                                        // RETURN THE PROGRESS
                                        echo $_SESSION['progress'];

The Client-Side Script

Once we have the server side of the application running, it's time to build the client side (the part that runs in the client's browser).  For this we use a conventional HTML5 web page.  These notes apply to the snippet below.


Line 8: This loads the latest "minified" jQuery framework.


Line 11-13: This starts the progress bar when the document.ready event fires.  In a real-world example, this might be started by a browser event, such as a mouse click.  But for our tests, it is nice to be able to refresh the browser and see the progress bar started immediately.  The script here tells the browser to run the loadProgressBar() function, and to address it to the div named #progressBar.  In theory it would be possible to have multiple progress bars on the page, but for this demonstration, one will do.  Note that for this example to work, the document.ready event handler is not required.  I only put it into the script as a placeholder since some other event might be the initial trigger for the progress bar.


Line 16: Sets the interval value to 1,000 milliseconds (one second).  Each time the interval timer expires, the script will call the server-side script for an update on the progress.  There is no hard-and-fast rule about a one-second interval; you can choose any values that makes sense for your needs.  You might want to experiment with faster or slower values.


Line 17: Sets the interval timer to call the function loadProgressBar() every time the intval expires.


Line 22: Defines the loadProgressBar() function.  The function takes one argument called "element."  This is the name of the outer wrapper div that encapsulates the progress bar.


Line 23: Every time loadProgressBar() is run, it calls the server-side script and retrieves an integer representing the percentage of completion of the background task.  This value is assigned to the JavaScript variable percent.


Line 24-28: If the percentage indicates that the progress is not yet complete, we recompute the width of the progress bar and animate the movement of the dark green background across the bar from left to right.


Line 29-36: When the percentage indicates that progress is complete, we are finished with the progress bar.  We take the following steps.

1. We remove the interval timer -- there is no need to call this function again.

2. We remove the background color from the progress bar.

3. We set the alignment to "center" and write "All Done!" in the middle of the progress bar

4. We use jQuery fade() and hide() functionality to cause the progress bar to act like the Cheshire Cat, disappearing from view.


Line 43-47: Our CSS defines the size and color of #progressBar div.


Line 49-57: Our CSS defines the div inside the #progressBar div.  It starts with a width of zero (which grows with each call to the loadProgressBar() function) and a background-color of dark green.  With this styling and the jQuery .animate() function, we can produce the visual effect of a progress bar that slides more-or-less smoothly across the screen.

 

3

Overview

This article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results.

The principle behind the design of this code is to re-use the same code to generate the table of results for both the first render and subsequent AJAX search requests. In this way changes to the table structure and layout only have to be managed in one place.

The Container Page

We start with the container page that displays the initial view of the data we are interested in manipulating through AJAX. The code below gives a basic structure for us to work with
index.php
<!doctype html>
<html>
<head>
<title>AJAX Sample search page</title>
</head>
<body>
  <h2>Super Hero Contact List</h2>
  Search <input type="text" id="search" /> <input type="button" value="Search" id="search_button" /><br/>
  <table id="superheros">
    <thead>
      <tr>
        <th>Firstname</th><th>Surname</th><th>Age</th><th>Email</th>
      </tr>
    </thead>
    <?php require_once('data.php'); ?>
  </table>
</body>
</html>

Open in new window


Rendering the results

The above page draws our Superhero contact list by calling an external PHP file (data.php) to render the actual rows of the table. Lets look at what data.php could look like
data.php
<?php
/* 
   FIRST: DEFINE OUR TEST DATA. 
   FOR OTHER IMPLEMENTATIONS THIS ARRAY 

Open in new window

2
 
LVL 57

Author Comment

by:Julian Hansen
Comment Utility
I suspect it is because it is finding 'bruce' in the email address. The search works by imploding the row - which includes the email. Bruce Wayne and Peter Parker both have their first name (lower case) in the email - while the others do not.

I suspect you should get the same result for Peter as for Bruce.
0
 
LVL 1

Expert Comment

by:RationalRabbit
Comment Utility
duh ... sure :0)
0
The Confluence of Individual Knowledge and the Collective Intelligence
At this writing (summer 2013) the term API has made its way into the popular lexicon of the English language.  A few years ago, the term would only be recognized by oil companies and a few geeky programmers.  But today, the term gives relevance and meaning to the "rise of the machines."  The explosion of online storage and computing power has given us a host of new applications that perform highly valuable, highly specialized functions, and that enable direct machine-to-machine communication.  The output from these applications can be used by other applications to deliver rich internet application experiences that are customized and personalized.  The information from these functions can underpin business decisions in advertising and marketing, in shipping and transportation, in medical diagnosis, and many other data-intensive endeavors.

In the context of our discussion here, when we refer to "API" we mean "web API" -- specifically the collection and dissemination of information via HTTP protocols.  These APIs let servers talk to each other in ways that build powerful online applications with relatively little effort for the developers.

Governments and companies like Google, Yahoo, Weather.com, MapQuest, UnderTone Networks, and many others gather, analyze, store, collate and publish detailed information …
6
 

Expert Comment

by:APD_Toronto
Comment Utility
Good Explanation!
0
 

Expert Comment

by:APD_Toronto
Comment Utility
Good Explanation!
0
The most up-to-date version of this article is on my Blog https://iconoun.com/blog/
3
 
LVL 38

Expert Comment

by:lherrou
Comment Utility
An elegant solution, and I can think of other ways to use it as well.

I voted YES above :)
0
Introduction
HyperText Transfer Protocol or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to the WWW in the days after 2005 (and therefore after the advent of jQuery), that seem to evince a misunderstanding of the way the HTTP protocol works.  Since HTTP is the basic building block of web sites and web applications, a clear understanding of the protocol is required to understand how web sites really work.  And perhaps more importantly, it is necessary to understand the protocol so you can build a web site that works like another site you've seen and appreciated.  This article is intended to lift the cloud of confusion that has appeared in the years since the arrival of jQuery, CSS3, animation in web sites, and the phenomenon called Web 2.0.

The confusion has arisen in large measure because of the design movement of web interactivity away from the static page loads and into design paradigms that more closely mimic native applications.  If the hyperlink was the design element that launched the internet revolution, the event handler may be thought of as the design element that has most refined the client experience.  In all cases, at the foundation is the HTTP protocol.

HTTP is a Stateless Client/Server Protocol
Client/Server protocols are two-way communication mechanisms that allow humans to get information from web sites
18
 
LVL 15

Expert Comment

by:ericpete
Comment Utility
Ray,

A typically outstanding article. I've been fumbling through telling people this stuff for a long time, so it's nice to have a clear resource to which to send them.

Thanks!

ep
0
jQuery is a JavaScript library that greatly simplifies JavaScript programming.

AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a new page load.  An HTTP request occurs, but it occurs as a result of a JavaScript event, rather than an explicit page load or form submission.  As a result, the web page takes on an appearance much like a desktop application, with smooth transitions as data is added or removed from the viewport.  This is often referred to as the "Web 2.0" effect.

I found myself looking around for a jQuery/AJAX "Hello World" example (that simplest of scripts to prove that the essential moving parts are working correctly).  There are lots of partial examples in many different places all over the WWW, but nothing seemed complete and well-documented, so I decided to write my own.  Here is the result of that effort.

The Server-Side of the Exercise
To make my example, I decided the essential parts would be the ability to send some data to the server and get a response back, so the first part of the exercise is the server-side script that produces a response containing the data it received from the AJAX request.  AJAX provides a RESTful interface.  The data for the request is sent via GET or POST and the response from the server is sent in the form of browser output.  As a result, it is very easy to test the back-end script. …
19
 

Expert Comment

by:Nico2011
Comment Utility
Thanks Ray - very helpful - hope you are well!
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
Comment Utility
It is very helpful.
0
Today I am discussing AJAX problems in IE7 and I bet this will helps many guys out here who have problems with AJAX work. Lets start with the discovery of problem and then we will talk about its different solutions.

My last two projects included AJAX work. In, first one, search result were displayed dynamically. It took me fewer hours to code that part of the project and when it started working ( in Firefox. I always recommend Firefox ), I was about to jump for joy. It was looking so cool and awesome and that "loading..." effect was fabulous. It was late night when I finished this task. So, after a few minutes of success I was in bed.

The next morning, when I was checking my task for bugs. I was really happy. Because it was working flawlessly. After testing in major browsers. last, step was to test this in IE. My heart starts beating really fast when I test my products in IE... :) Hopefully you know why.

Tested in IE8..result: passed!...Tested in IE7...result PASSED....Oh! oh! wait a minute. It just accepted first AJAX call and it is doing nothing for next AJAX calls in IE7. I was hooked at the edge. What the hell dude! I was about to finalize this part :(

Then I tried to make tweaks in code to make it work. Like changing sequence of function calls, opening connection, writing success function and then sending request and different other sequence.

After searching some solutions and reasons for this on Google and hitting wall hard throughout the day. Finally, I …
2
 
LVL 3

Author Comment

by:aqif_g
Comment Utility
Thnx for your words and suggestions. I have made some changes as per your requirements. Hopefully, it is fine now.

regards,
aqid
0
Independent Software Vendors: We Want Your Opinion
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

There is basically two types of AJAX request in mootools.

Request  and Request.HTML

Request:


Request is the basic XHR request class in MooTools. While not extremely useful on its own, it provides the basic functionality for both Request.HTML and Request.JSON.

Demo Code:

var req = new Request({
url: demo_path + ‘data.txt’,
onSuccess: function(txt){
$(‘result’).set(‘text’, txt);
},
// Our request will most likely succeed, but just in case, we’ll add an
// onFailure method which will let the user know what happened.
onFailure: function(){
$(‘result’).set(‘text’, ‘The request failed.’);
}
});

req.send();

Open in new window


Request.HTML:

Request.HTML is a subclass of Request built for making XHR requests which return HTML content.

Demo Code:


var req = new Request.HTML({url:demo_path+’data.html’,
onSuccess: function(html) {
//Clear the text currently inside the results div.
$(‘result’).set(‘text’, ”);
//Inject the new DOM elements into the results div.
$(‘result’).adopt(html);
},
//Our request will most likely succeed, but just in case, we’ll add an
//onFailure method which will let the user know what happened.
onFailure: function() {
$(‘result’).set(‘text’, ‘The request failed.’);
}
});

req.send();

Open in new window


Another parameter for Request.HTML is as below:
update:$(‘id_of_element’);

Open in new window


Here id of the element should be passed, and what ever the response will be placed inside the given element ID.
----------------------------------------------------------- --------------------------------- --------------------------

Smooth Scroll in mootools 1.2


How to scroll to the top of the page or any portion of the page very smoothly?

here is the solution for that. Please check.

When we use anchor link to go to specific portion of the then browser jurks to that portion of the page.

Below mootools plugin is useful to scroll the page very smoothly.

Mootools have in built plugin to get page scrolled smoothly as you want.

Below are the steps to include that:

Include mootools1.2 in your file, if you don’t have download it from mootools site
To enable the scroll plugin add the below code in your head section after including mootools JS


Open in new window

0
ASP.NET AJAX callbacks to web service are becoming very popular and unavoidable these days. The feel that the user gets when only a part of the page is updated without even hindering the UI is the advantage that the callbacks offer. The wait for the full page to be posted back and results to appear is reduced thereby keeping a rich user experience. In some situations you would not want to expose the arguments and the methods it supports to the public through the ASMX file. This will require you to move the logic to specific ASPX files or inside the inherited base class. Specifically, this is the most important reason which, I feel, would require you to move web methods to ASPX pages.

Both ASP.NET AJAX Extensions and ASP.NET 3.5 support AJAX callbacks to the web methods placed in ASPX pages or the inherited base class. The following are the steps involved, and we will use a fictitious routine "GetEmployees" to exemplify what we are doing.

The first step is to expose GetEmployees as a web method.

 
1: public partial class Employees : System.Web.UI.Page
2: {
3: [WebMethod]
4: [ScriptMethod]
5: public static List<Employees> GetEmployees(string dept)
6: {
7:   // logic to get the Employee list
8: }

Open in new window


Important points to be noted :

1. The method needs to be decorated with [WebMethod]
2. The method needs to be decorated with [ScriptMethod] to enable callback
3. The method MUST be static

Go to ScriptManager tag and set the …
2
 
LVL 21

Author Comment

by:masterpass
Comment Utility
No need to add a new item to your project if you are going with pageMethods .. you can just add this in the code behind of the aspx file
0
 

Expert Comment

by:nicedone
Comment Utility
I get an error in my code below altough i took what you mentioned as a reference can u help me on where i made my mistake on?

@masterpass

you said

one thing that wont work in your code is System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");

but i still get undefined error altough i took your reference as a guide so what should i do ?

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            string hasta_adi = e.CommandArgument.ToString();
            
            // Write code to delete data from SQL
            // if this patient will be deleted what should be done is 
            //\\//\\//\\//\\//\\//\\//\\\//\\/\\/\\/\/\/\/\/
            bool i = checkpatientexists(hasta_adi);

            //if i is true that means operations exist with this patient ,warn the user again 
            //if user confirms again then proceed with deletion. !!!

         if (i == true)
         {
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')==true){document.writeln('true');}else{document.writeln('false')}</SCRIPT>");
         
             Button btnDelete = e.Item.FindControl("btnDelete") as Button;

         // btnDelete.Attributes.Add("onclick", "return confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')");
         //  System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('Hastaya ait Operasyonlar bulunmaktadir...'+ btnDelete.CommandArgument.ToString()) </SCRIPT>");
         //  Response.Write("pressed OK");
          
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> alert('Hit OK')</SCRIPT>");

          System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait Operasyonlar bulunmaktadir ==>>" + btnDelete.CommandArgument.ToString() + "')==true){ PageMethods.M1(); };</SCRIPT>");
             
         //System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('" + btnDelete.CommandArgument.ToString() + "'adli hastaya ait operasyon(lar) bulunmaktadir...');</SCRIPT>");
         }
        }
    }
    [System.Web.Services.WebMethod]
    [ScriptMethod]
    public static void  M1()
    {
       // System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");
        string s = "Fatih Dikili";

        //return Class1.M2();
    }

Open in new window

0
Hello World !,

Thanks :
My Sincere thanks to @Michael Male who encouraged me to write an article on this in my  blog.


Introduction:

      There are several technical issues a developer may face in his everyday routine. Many of it would be as itchy as dandruff  :) , and there are always different ways a particular problem can be solved or dealt with. But, the best /recommended approach works fine in most of the cases.
       
        One such issue is when a web session expires without any prior notice to the user, who might be busy talking in a meeting, chatting (of course official), answering a phone call, or just out for a quick walk. The returning user might be annoyed if the page says that "Your session expired" after keying in a long form of data. If you've experienced this (and who hasn't), you know how annoying it can be.

        So, I present here one possible solution of addressing this using AJAX. Let's get down to business straight away.

The Ajax way:

     This article is intended primarily for readers who are aware of AJAX (at least at a basic level), so I will go directly to the functional part of the solution.

function newXMLHttpRequest()
{
        var xmlreq = false;    
        if (window.XMLHttpRequest)
        {
          xmlreq = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            try
            {
               

Open in new window

1

AJAX

12K

Solutions

13

Articles & Videos

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.