The Power of jQuery with Ajax


As the web evolves, new technologies are emerging and uniting in remarkable ways. The combination of Ajax and jQuery, in particular, is one of the most powerful unions to date.

The purpose of this article is to give a brief and generalized overview of both Ajax and jQuery, and also discuss how jQuery has made Ajax development easier than ever before.

What is Ajax?

Since its conception in 2005[1], Ajax (Asynchronous JavaScript and XML) has changed the web as we know it today. It’s helped websites evolve into Rich Internet Applications (RIAs) by allowing web pages to make direct requests to web servers without reloading the page. This capability is vital in replicating the rich user experiences achieved in client applications.

Ajax in Practice

Let’s say that you have a login form for your web application. To ensure that the provided login name and password entered by the user is a match without using Ajax, your web application would have to load a whole new web page that shows an account screen if the login was successful, or show an error screen if the login failed. This is the old way of handling logins.

A more savvy approach to this problem would be to check if the login and password is correct using Ajax.

Here’s how Ajax would work in this instance: Once the user has typed in a login name and password and submitted the login web form, you could have a JavaScript function that invokes an Ajax call that sends two parameters — the login name and password.

The web server (usually through a server-side script/language such as PHP) takes the two parameters and then queries your user database to see if there is a match.

If there is a match found in your database, then the web server can return a success flag. Otherwise, the web server could return an error message.

Next, you would then have a JavaScript function that accepts the Ajax response. If the response is successful, it could use window.location to send the user to their account screen.

If the response contains an error message, the application can display the error on the screen without ever reloading the page.

The main thing to take away from this is that you don’t have to reload an entire page just to handle username/password verification, making your web application more responsive and, if the page is heavy, saving you some significant bandwidth.

What is jQuery?

Released in January of 2006[2], jQuery is a cross-browser JavaScript library designed to simplify the client-side script of HTML.

Used by close to a million websites[3], jQuery is the most popular JavaScript library in use to date.

jQuery makes it easy to handle DOM objects, events, effects and Ajax, automatically takes care of JavaScript leaks, and has countless third-party plugins.

The Problem with Ajax

Despite its revolutionary impact on the web, Ajax can be difficult to use even for veteran developers.

People will usually create their own custom functions to handle Ajax calls so that the functionality can be reused across a web application. This can become very tedious when a web application makes use of different types of Ajax calls — such as the ability to handle both synchronous and asynchronous calls — or the ability to handle different response formats such as string messages, HTML, CSV, XML, JSON, etc.

As a professional web developer, I’ve personally spent countless hours building custom methods to handle Ajax calls.

Traditional Ajax calls usually take on the following form:

function httpRequest(id) {
  if (window.XMLHttpRequest) { // code for IE7+, FF, Chrome, Opera, Safari
    http=new XMLHttpRequest();
  }
  else { // code for IE6, IE5
    http=new ActiveXObject("Microsoft.XMLHTTP”);
  }
  http.onreadystatechange=function() {
    if (http.readyState==4 && http.status==200) {
      response = http.responseText;
      // do something with response
    }
  }
  dest=”servlet.php?id=” + id;
  http.open("GET”, dest);
  http.send();
}

If your web application only uses one Ajax call, it’s not that big of a deal to implement. The problem occurs, however, when your web application leverages lots of Ajax calls and you try to break the code apart to make it reusable.

The idea of Ajax is to send a request to some web server, wait for a response, and update your HTML page. It would be convenient to create a custom function like httpRequest() that takes two parameters — a request URL and a response function — that could be reused throughout your system.

Once you start setting this up, however, you’ll immediately see that the simple task of making an Ajax call suddenly becomes a nightmare when you try to construct response function evaluations using eval() and figuring out how to make your new function handle synchronous calls, asynchronous calls, and different response formats.

At the end of the day, the simple idea of creating a custom httpRequest() function quickly turns into a big project.

The other advantage of jQuery is that it has additional Ajax functions and methods that you can use, which can further reduce development and debugging time.

Hello Ajax. Meet jQuery.

Among other advantages, one of my favorite features of jQuery is its ability to leverage Ajax with very little effort. To make an Ajax call, you can do something like this:

$.Ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
    alert( "Data Saved: " + msg );
  }
});

If you’ve developed Ajax applications before without jQuery, you’ll immediately see the value here. jQuery has put all of the properties of Ajax into one simple API. You can control everything including the url, cache, success function, data type, and even synchronization, all from one neat declaration. It’s nothing short of beautiful.

Get Started with Ajax + jQuery

If you’re not using a JavaScript Web Development framework like jQuery or MooTools yet, and you’re planning on creating responsive web applications, you should leverage these awesome libraries.

For jQuery, the following list highlights some tutorials you can check out.

References

  1. Ajax: A New Approach to Web Applications
  2. jQuery 1.0
  3. jQuery Usage Statistics

Related Content

About the Author

Eric Rowell is a professional web developer and designer who is fascinated with everything related to the web, including RIAs, emerging technology, and social media marketing. He is the Founder and Chief Editor of Web Krunk and loves HTML, HTML5, CSS, JavaScript, Ajax, jQuery, Flash, PHP and Java. You can follow him on Twitter at @webkrunk.

Enhanced by Zemanta
About these ads

Etiquetado:, , , , , , , ,

Cruces, Sol y La Imaginación

Cuando la imaginación y la creatividad suman infinito

MarketingActivo

el mundo del marketing se activa para ti

tranquicomix

fanzine bejarano de historietas hecho en los 80

A Stairway To Fashion

contact: ralucastoica23@gmail.com

Vinod833's Blog

This WordPress.com site is the bee's knees

Apasionada de las Redes Sociales

Compartir conocimientos 2.0 y Marketing Online

Zona de Promesas

Tecnología - Internet - Redes Sociales - Entrepreneurship - Música - Economía - Innovación

Top Master | Blog

LOS PROGRAMAS DE MBA Y POSTGRADO MAS INFLUYENTES DE TODO EL MUNDO

La realidad alterna

Diario de sueños, cuentos, poesías y una novela en proceso

TechCrunch

Startup and Technology News

Unencumbered by Facts

Taking unsubstantiation to new levels

Carlos Cordero

Blog de tecnología

PsicoEmocions Blog

Un Pont entre la Psique i les Emocions

TEA PTLS NACHO

AUTISMO.TEA..PTLS

Comunicación & Marketing

De Lilian Lanzieri

Xtratexia

Dirección estratégica para la vida

Silvia Altamirano

An editorial designer that writes

StellarHIRE Partners

Founding Partner, StellarHire Partners - Executive Search Consultants. Recent engagements include Eloqua, SFDC, Tibco and Veeam.

ivanbrunpr's Blog

4 out of 5 dentists recommend this WordPress.com site

Matt on Not-WordPress

Stuff and things.

BLOGTEC

Noticias de Tecnologia.

Talento en Expansión

Tendencias y Mejores Prácticas en la Gestión de Personas de la Empresa 2.0

Two Leaves Tea SPAIN

Great Organic Tea! ✫✫✫✫✫ Te Organico en Piramides

Escuela de Dinero

El mejor Sitio en Español sobre lo básico para entender el Dinero y sus matemáticas relacionadas.

Intentando dejar huella...

...en cada uno de los visitantes

Ideas Para la Clase.com

Portafolio de experiencias en la clase de español para Middle School.

littlegreybox

Travel & Lifestyle Blog

déborah rueda

Un sitio más pero diferente sobre marketing on line

No solo los 80's

La mejor música de la historia

Molly Balloon's Blog

Identity + Dressing + Colour

El OJO PUBLICO. / Глаз общественности

Ver para contar & contar para ver. / Чтобы рассказать

Think Creative Idea

Marketing, publicidad, web y negocios

Social Media y más

Social Media, Redes Sociales, Marketing, SEO

The Coaching Alliance

El camino hacia el éxito

Luces y sombras de las marcas

Social Media, Marketing y Comunicación

CNN en Español: Ultimas Noticias de Estados Unidos, Latinoamérica y el Mundo, Opinión y Videos

Ultimas Noticias de Estados Unidos, Latinoamérica y el Mundo, Opinión y Videos

Javier GM Photography - México y más.

“Un fotógrafo tiene que ser auténtico y en su obra, debe expresar emociones, provocar reacciones y despertar pasiones.” ~ Javier García-Moreno E.

Natalia Gómez del Pozuelo

Experta en comunicación y oratoria

aloyn

Alimentación, ocio y negocios, ALOYN, es un Grupo dirigido a Directivos y Propietarios de empresas, interesados en el mundo de la industria de alimentación y bebidas. Tanto por la parte de la industria productora como por la parte de la industria consumidora y/o distribuidora (Distribución Comercial, Horeca, Vending, Venta Directa, etc). También nos interesan las actividades ligadas al agroturismo y el enoturismo como magníficas actividades de promoción y difusión de la cultura gastronómica.

Blog de Jack Moreno

Un blog de Joaquín Moreno sobre recursos, literatura y ciencia ficción

Mashamour

Ensalada de Manjares

Infographic List

For those who love Infographics - www.infographiclist.com

URieLaRtE

hay que ser libre para ser uno mismo

Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 1.682 seguidores

%d personas les gusta esto: