Share On Twitter Facebook Google+ LinkedIn Pinterest Tumblr Reddit
Question

What can I use instead of Ajax?

Tags: ajax javascript
Date:
Status:Unresolved
Question Id:33

I need a simple ajax tutorial for a input form, where I want to post a username through an input form, which sends it to the database and replies with the results.
Any recommendation for such tutorial is welcome, because I've only got one using Mootool but I'm searching for one using jQuery!

Answer
Date:
Correct:No

You can try this:

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

This code will append the content of test.html file to #results element

You can find more information at jQuery website.

 

Use this code to send POST data and output result.

var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  $("#log").html( msg );
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});
Answer
Date:
Correct:No

All of the answers here are mostly correct and there's not a lot to say about this question in the first place, but just to clarify: ajax stands for Asynchronous JavaScript and XML. The term came from a time when XML was thought to be superior and a succession to HTML, so really this last term is a bit misleading. It's just meant to reference the fact that the HTML could be changed and rendered through data transfer alone, which is mostly done in JSON now. Asynchronous means that it's time interleaving. It will wait to process the request as it receives enough data and continue to work respond to user interaction in the mean time. It also won't reload the entire page. This was really important when we didn't have the ability to ship the entire application to the client in the first place and execute it from that side.

We still use AJAX, but it's several layers removed from what you actually have to worry about in implementation of an application today. AngularJS and other available libraries make it easy to avoid writing the actual AJAX call and structuring both sides of the application to recieve it well and instead encapsulate that functionality in the common route and view model paradigm of modern web applications. In these applications, RESTful APIs are used to transact data, often in JSON and sometimes in XML. RESTful APIs provide a more conceptual implementation that fits HTTP well. Alex Deva mentioned Web Sockets, which is certainly a better option and well supported, but is slightly more work. Because of this, publicly exposed APIs are often just left as RESTful services, but internal APIs meant for the application and server only are often done with WebSockets. DDP is a newer method of using persistent WebSockets to host sessions of data transfer for much less overhead. So, it's not that we use something different than AJAX really, it's that we've moved on from requiring it to be XML or even doing the AJAX call manually to completely abstracting it to a low level high throughput distributed data subscription and publishing service. You should be familiar with implementations of RESTful services and websockets, and the concept of ajax.

Answer
Date:
Correct:No

Ajax is not a one thing, it is a method. You don’t need to use jQuery, you can use Angular and many other things. It is just a description of a technique to fetch data from a server without doing a page refresh. There are literally hundreds if not thousands of toolkits out there to make this ob easier or harder.

I really wanted to first answer this question with : Fresh air, sex, good hamburger or just food. But that would be rude.

Answer
Date:
Correct:No

there is also async api that all of the modern browsers support it

 

fetch('./api/projects',
  {
    method: 'post',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'Beispielprojekt',
      url: 'http://www.example.com',
    })
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.error(error);
  });
Answer
Date:
Correct:No

Yes there are some other ways to call ajax

jQuery

var get_data = function(){
    var result = false;
    $.get('/rest/computer').done(function(awesome_data){
        result = awesome_data;
    });

    return result;
}

$.getJSON

$.getJSON( '/rest/computer', { assessmentId:"123", classroomId:"234"})
  .done( function(resp){
    // handle response here
}).fail(function(){
   alert('Oooops');
});

If you're not using jQuery in your code, this answer is for you

Your code should be something along the lines of this:

function foo() {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', "/rest/computer");
    httpRequest.send();
    return httpRequest.responseText;
}

var result = foo(); // always ends up being 'undefined'
Answer
Date:
Correct:No

AJAX is the most popular, easiest and still very powerful. There are also many built-in libraries or libraries that contain powerful tools for HTTP calls like jQuery AJAXaxiosfetch and I'm sure there are many more depending on the language you're working with.

Considering you're talking about dynamic web pages and AJAX, I'm assuming you're using JavaScript and need to work with data to/from a server dynamically (without refreshing).

There are many ways to do this, but they all differ in their abilities. I'll explain a few and why you may want to choose one over another.

AJAX

It seems like you've worked with AJAX before, but I'll explain it anyway for curious parties.

AJAX is Asynchronous JavaScript and XML. It allows you to make an HTTP call from the client (your browser) to a server (your back end built in C#, Java, PHP, NodeJS, Python, etc.) without refreshing the page because it's asynchronous. That means it's able to operate "outside" of your current process, so it can make the call without interrupting the current process (refreshing) and get a response and use it to update your current process. When AJAX was first created, it was common to use XML to send data over HTTP because it's structure and ability to define objects, however, you can send many different types of data including plain text. Because of how complex XML can be, many APIs have switched to using JSON, JSON is JavaScript Object Notation which is very simple to read, can be represented easily in plain text and therefore parsed relatively easily and works seamlessly with JavaScript. Many languages have native libraries for JSON now. Other formats for sending data are YAML, XAML and I'm sure there are more.

The main thing to remember about AJAX is that it sends a call to the server and then receives a response, but it only receives data from the server when a call is sent. Therefore it is unidirectional meaning, data must be requested before it is received.

Server Sent Events

AJAX is useful for certain applications that don't update often so it can be called with a timer or when the user requests an update (if you use social media, you may notice it notifies the user when new data is available). For a small application, this is really powerful, but on a production scale for something as large as a social media platform like Instagram, Facebook or YouTube, that could be very taxing on a web server that serves millions of requests per hour, so if it's on a timer that is called every 30 seconds that means every 30 seconds each active user (potentially millions), would make a request to the server (more like a cluster of servers tied together, but the point still stands). That's not efficient nor is it scalable. There are ways around it with AJAX which I'll get to and were workarounds in the early days of AJAX, but there have since been new technologies made available.

Server Sent Events is a really powerful tool that is somewhat similar to AJAX in that it creates a call and is unidirectional, but it works in the other direction. Essentially, the client makes a call to the server just like AJAX, BUT the difference is that the server responds with an event stream and essentially keeps the connection open. The connection is not closed and so when the server has new data (that you push to the event stream), it will send an event to the client with the data. This is very useful for an application that has a lot of real time data without much input from the user. A good example of this would be a news site that provides information about the weather. Instead of the user refreshing for new information or the client sending multiple requests, the client simply subscribes to the event source and when the data is available, the server sends it to the client.

Server Sent Events are really useful for certain applications, but I can attest (because I've implemented them myself) that they are difficult to implement properly and there are a lot of bad tutorials online. The most popular search results return guides that close and open the connection in between each request in turn defeating the purpose of Server Sent Events.

I would not suggest implementing server sent events unless you have a good understanding of JavaScript, the server-side language / technology you're using (C#, Java, NodeJS, PHP, etc.) and HTTP in general.

WebSockets

The problem with AJAX and Server Sent Events being unidirectional is the case of real-time applications. Imagine a chat application where you had to refresh the page or click a button or wait 30 seconds to see if someone replied, it would be annoying and not very user friendly. This is why AJAX is not very useful for real-time applications. There are workarounds for this such as polling, long polling or a combination of Server Sent Events and AJAX, but at last it is 2020 and WebSockets have shown up to the party.

WebSockets are a "newer" technology (introduced around 2010 and added to all browsers some time in the last decade) that allow for a client and a server to have a bi-directional connection by literally "upgrading" the HTTP connection. That means the client can send calls to the server, and the server can send calls to the client. That is very powerful and is why WebSockets are becoming increasingly popular with uses by Discord, agar.ioslither.io and I'm sure many others are out there as well as some that are on the horizon.

There are popular WebSocket server libraries like Socket.io, SignalR (not a fan) and ws. The best part about WebSockets is that it is native to the client (JavaScript), so you don't need to add anything to your project to use it in your JavaScript code.

Honorable Mentions

As promised, I will mention some workarounds in case you do need "real-time"-ish apps, but are not ready to make a WebSocket server (though it's very easy depending on the server-side language you're using).

Polling

Polling is pretty self-explanatory. The idea is that using AJAX, you'd keep making requests to the server until new data is available. Easy to implement, but pretty inefficient especially in a larger scale production environment. Not scalable at all.

Long Polling

Once again, pretty self-explanatory. The idea is that using AJAX, you'd keep making requests to the server until new data is available, BUT on the server side you wouldn't respond until their is new data. There's always a limit though and you can't keep a connection open until there is new data, what if it takes hours for new data to be available. In a dynamic application, you'd never know, that's what makes it dynamic. Still pretty easy to implement with a little extra work from the server, but still inefficient. Also, not scalable at all.

These workarounds were prominent and useful before WebSockets were available. I recommend that if you need to make a real-time application, you study the type of application and where your use case actually applies.

It's important to note that WebSockets aren't a replacement for AJAX. AJAX still has many use cases and is used widely for large scale applications. WebSockets are ONLY useful for real-time applications where you need data to be sent back and forth between the server and client for a period of time. You can and should still use AJAX until something better (if ever) is available. Even if you have a real-time application, a mix of both may be useful depending on the use case.

Understand your application's needs before making a decision.

tl;dr you can use WebSockets, Server Sent Events, Long Polling or Polling, but WebSockets and Server Sent Events are not a replacement of AJAX.

Your Answer

Review Your Answer