DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Better Scaffolding with jQuery - Part I
  • An Introduction to Type Safety in JavaScript With Prisma
  • DocRaptor vs. WeasyPrint: A PDF Export Showdown
  • 6 Tips to Help You Write Cleaner Code in Node.js

Trending

  • 10 Tips To Improve Python Coding Skills in 2024
  • Implementing Persistence With Clean Architecture
  • Architectural Insights: Designing Efficient Multi-Layered Caching With Instagram Example
  • Types of Bot Traffic on a Public Internet Website
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Return Ajax Response From Asynchronous JavaScript Call: Methods and Code Examples

How to Return Ajax Response From Asynchronous JavaScript Call: Methods and Code Examples

In this article, we take a look at three different ways that web developers can go about using Ajax in their applications, and give some sample code.

By 
Angela Stringfellow user avatar
Angela Stringfellow
·
Aug. 31, 17 · Analysis
Like (4)
Save
Tweet
Share
42.5K Views

Join the DZone community and get the full member experience.

Join For Free

When JavaScript is used in conjunction with XML or REST APIs, you can create some useful behaviors with a set of web-development techniques collectively known as Ajax. Let's take a look at a specific Ajax functionality: returning an Ajax response from an asynchronous JavaScript call.

First, What Is Ajax?

Asynchronous JavaScript and XML, or Ajax, isn't a new technology in itself, and it's not a programming language. The term was coined back in 2005 by Jesse James Garrett. As the Mozilla Developer Network explains, Ajax "describes a 'new' approach to using a number of existing technologies together, including HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and most importantly the XMLHttpRequest object."

Screenshot via W3Schools.com

Essentially, it serves as a bridge between database and server without requiring the user to refresh the page. It is a better way to create faster, more responsive, and better web-based applications using HTML, Java Script, XML or JSON, and CSS. Using Ajax, a page is able to request things from the server, process the results, and then update the page - all of which happens without the user sensing what's going on or having to take additional actions.

Where Is Ajax Used?

Ajax is commonly used in Web applications where small tidbits of information are retrieved or saved without needing to reload an entire page. Take, for example, saving a comment on a message board. Ajax is also used on auto-complete boxes and text hints, where you can type the first letters and the system would try to guess what you are typing and suggest words or phrases for you.

Note that while the "X" in Ajax represents XML, JSON is more commonly used today as it's both lightweight and a part of JavaScript. However, both JSON and XML can be used to package information in the Ajax model. In addition to JSON and XML, data can also be transported as plain text.

Challenges of Asynchronous Methods Like Ajax

Asynchronous methods cannot easily return its value, unlike traditional methods. This is because the results are computed asynchronously or in such a way that one operation begins only when the previous operation has been completed, so the method might have returned before the result is calculated.

If you use multi-threads, you can easily get around this by synchronously waiting for the asynchronous operation to terminate. But that would mean you wouldn't be able to take full advantage of the benefits of asynchronicity.

Asynchronous methods allow you to free up the thread even when the operation is still running. In JavaScript and other single thread languages, there is also no way to go around this because a waiting method means that a result would never be arrived at.

How to Use Asynchronous Methods in Ajax

Ajax is a very well known method for loading the content of a Web page without manually refreshing it. But the letter "A" in Ajax means asynchronous, meaning that you need to have a callback function that will return the results.

You can always use a synchronous call, but that will freeze your page and maybe turn off some of your users. You can think of synchronous methods like making a telephone call and being put on hold while the call is being redirected to the person you want to talk to. While on hold, there is nothing that you can do but just wait until the other party speaks.

This means that if you have any other code next to var item = findItem(); these would not execute unless the function gives a result.

Now for asynchronous methods, let's go back to the phone call example. For instance, you call somebody you want to talk to, but the person is not available, so you leave a message to have him or her call you back. This way, you no longer have to wait on the phone listening to the hold music, you can do other things until the person returns your call. Ajax requests do just that.

With this, all codes following this one will execute immediately; you will not have to wait until the function returns. This way, your user would not have to wait for findItem() to return a result. Of course, because you still need an answer, you would have to include a callback. A callback is a function that would give you the result or response you wanted, and it is typically called after all statements after the findItem() has been executed.

Solution 1: Making Synchronous AJAX Calls

The first solution has already been mentioned above. You can write asynchronous AJAX calls so that it waits for the response before moving on to the next statements. If you are using jQuery, you can easily do this by setting the async option to false.

Image title

However, if you are not using jQuery, like when you use $.getJSON, $.get, and others, you will need to revise it to $.ajax and then use async: .open instead of async: false if you are using an XMLHTTPREQUEST object.

Moreover, if you are using JSONP, you will not be able to create a synchronous JSONP call because JSONP is, by default, asynchronous.

While this might help you solve the problem of getting a return response to your Ajax call, there is no doubt that you will run into problems using this solution. For one, if there are any long processes in a JavaScript code, it will lock the user interface and make it unresponsive.

JavaScript execution times are also limited, and when it reaches its limit, the browser will prompt the user to ask whether he or she wants to continue executing the code or not. Both the browser hanging and a pop-up window asking the user to continue, translate to a bad user experience. What's more, the user will have no way of telling if the code is working all right or if it has crashed the browser. This is especially true with users who have a slow Internet connection.

Solution 2: Make Functions Accept Callbacks

A much better solution is to make your functions accept callbacks and rewrite your code around these.

Here's an example from <node-tricks]. If you have:

Image title

You should write it as:

Image title

This will make the foo accept a callback, which it will then use as success callback. Then you can set up a function as an argument to foo, like this:

Image title

Then define foo as:

Image title

When this code executes, callback will go back to the original function that we have set up to foo. $.ajax will call the callback function and give the response.

Solution 3: Deferred Objects

There are times when directly passing a callback is not ideal for your application. The good news is that for these situations, you can rely on deferred objects or those that represent a value that may be available at a certain point in the future. Deferred objects make use of a then() method when you're passing a callback so that it will execute when the value becomes available. In short, using deferred objects, you can chain your Ajax calls without nesting any part of your code.

code style JavaScript

Published at DZone with permission of Angela Stringfellow, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Better Scaffolding with jQuery - Part I
  • An Introduction to Type Safety in JavaScript With Prisma
  • DocRaptor vs. WeasyPrint: A PDF Export Showdown
  • 6 Tips to Help You Write Cleaner Code in Node.js

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: