Table of contents
1.
Introduction
2.
Ajax Web Application
3.
Traditional web Application
4.
Implementation of Ajax in cherrypy
4.1.
Ajax Program CSS
4.2.
Ajax Program HTML
4.3.
Ajax Program Python
4.4.
Output
5.
Frequently Asked Questions
5.1.
What are the features of AJAX?
5.2.
What differentiates AJAX from other technologies?
5.3.
How many languages does AJAX combine?
6.
Conclusion
Last Updated: Mar 27, 2024

Make it smoother with Ajax in cherrypy

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In recent years, web applications have gotten away from the straightforward "HTML pages + refresh the whole page" approach. This time-tested method is still quite effective, but consumers are accustomed to web programmes that do not refresh the entire page. Client-side code in web apps allows them to communicate with the backend without refreshing the page. The same is made possible via Ajax.

Ajax Web Application

In an Ajax in cherrypy web application, the entire page must be loaded after a client performs a request and receives a response. Only a portion of the page is refreshed when the client makes another request after the server answers. The server may respond to the client's request with a partial page refresh. User interaction with a web application with Ajax in cherrypy initiates communication behind the scenes. The server requests the information required to update the page and does not return the entire HTML code for the web page. This action takes place asynchronously. The browser only updates the pertinent area of the webpage.

Traditional web Application

Let us See how a conventional web application functions. On a server, we have a client. The server returns the entire page in response to the client's request. The server will reply with the full HTML if the client sends the request again. It is necessary to refresh the page completely. The client then waits for the server to respond after sending a request. The entire webpage needs to be reloaded after receiving the response. This is an example of a typical classic web application without Ajax in cherrypy. Traditional web applications are easy to develop and do not require extensive programming. Traditional web apps, however, take longer. Typical web applications repeatedly communicate data as a request and response to display an entire web page. Reloading the entire web page is necessary, depending on the response.

Implementation of Ajax in cherrypy

We will create a straightforward client-side application to calculate a number's cube. Four HTTP requests will be made by the application to calculate the cube. Let us see how Ajax in cherrypy gets used in real-world settings.

Ajax Program CSS

First, we must ensure that we save the CSS code below in a file called "style.css" located in the "public/css" directory.

body {
  color: rgb(0, 0, 0);
  background-color: rgb(233, 185, 255);
}

#cubeValue {
  display: none;
}

Ajax Program HTML

We will utilise the jQuery framework for the application's home page to keep things simple. However, the users can switch it out with their programme. Simple HTML elements are used on the page to collect user input and display the resulting string. Additionally, it has client-side code to communicate with the backend API that does the labour-intensive job.

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Ninjas: AJAX</title>
    <link href="style.css" rel="stylesheet" />
    <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#calculateCube").click(function (e) {
          $.post("/cube", {
            number: $("input[name='number']").val(),
          }).done(function (cubeValue) {
            $("#cubeValue").show();
            $("#cubeValue input").val(cubeValue);
          });
          e.preventDefault();
        });

        $("#replaceValue").click(function (e) {
          $.ajax({
            type: "PUT",
            url: "/cube",
            data: { number: $("#cubeValue input").val() },
          }).done(function () {
            alert("Replaced the Value!");
          });
          e.preventDefault();
        });

        $("#deleteValue").click(function (e) {
          $.ajax({
            type: "DELETE",
            url: "/cube",
          }).done(function () {
            $("#cubeValue").hide();
          });
          e.preventDefault();
        });
      });
    </script>
  </head>

  <body>
    <input type="text" value="5" name="number" />
    <br><br>
    <button id="calculateCube">Calculate the Cube Value</button>
    <div id="cubeValue">
      <input type="text" />
      <br><br>
      <button id="replaceValue">Replace result</button>
      <br><br>
      <button id="deleteValue">Delete result</button>
    </div>
  </body>
</html>

Now we have to save the above code in the index.html file.

Ajax Program Python

We have written the HTML code for our AJAX in cherrypy web application. Now we have to write the Python code that drives the page. The application's code that delivers the HTML page and responds to requests to compute the cube of a number will then be written.

import cherrypy
import os


class application:
    @cherrypy.expose
    def index(home):
        return open('index.html')


@cherrypy.expose
class applicationWebService:

    @cherrypy.tools.accept(media='text/plain')
    def GET(home):
        return cherrypy.session['output']

    def POST(home, integer=3):
        answer = str(int(integer)**3)
        cherrypy.session['output'] = answer
        return cherrypy.session['output']

    def PUT(home, integer):
        cherrypy.session['output'] = integer

    def DELETE(home):
        cherrypy.session.pop('output', None)


if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/cube': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    webapplication = application()
    webapplication.cube = applicationWebService()
    cherrypy.quickstart(webapplication, '/', conf)
You can also try this code with Online Python Compiler
Run Code

We should save the above code in the name "ajax app.py".

Output

Run the following command in the Terminal or Command Line: "python3 ajax app.py"
If we type "http://localhost:8080/" into a browser's address bar, the result will look like this. The default input is given as "5". This can be changed according to the user's wishes.

default result

Below, we can see that the cube of the number requested has been shown in this instance. By selecting the "Replace result" and "Delete result" buttons, we may carry out the other HTTP requests, PUT and DELETE.

output obtained upon pressing the calculate button

We can also quickly figure out how the whole page has not been refreshed. Instead, the position of the page required got refreshed. We have illustrated how Ajax in cherrypy implementation is carried out using a straightforward example.

Frequently Asked Questions

What are the features of AJAX?

The most attractive aspect of AJAX is its "asynchronous" nature. This allows AJAX to exchange data with the server and update the page without requiring a whole page refresh. The following are some things that AJAX's two main features enable: Without refreshing the page, send requests to the server.

What differentiates AJAX from other technologies?

With XML, HTML, CSS, and JavaScript, a new method called AJAX enables the development of more effective, quick, and interactive web applications. In addition to Document Object Model and JavaScript for dynamic content display, Ajax leverages XHTML for content, CSS for presentation, and other technologies.

How many languages does AJAX combine?

AJAX (Asynchronous JavaScript and XML) is a method for building interactive web programmes that are better and faster. It is done by integrating JavaScript, dynamic HTML (DHTML), and extensible markup language (XML).

Conclusion

Ajax is used to convert static web applications into responsive ones, which offers several advantages. Ajax in cherrypy has drawbacks in addition to its advantages. Programming complexity is the first difficulty. In some cases, JavaScript must be integrated. An ajax object must be created. Along with this, sometimes function expressions must be written. Then the data must be handled to develop an exact programme. Along with user experience, we also have network-related issues. However, keeping in mind its swift use, Ajax in cherrypy is a handy tool. In this article, we read and discovered how it is better than traditional web applications. We also implemented a simple application in Ajax in cherrypy to show its real-world use. You can read how to build applications with Python and find the basics of python here. Do not forget to check out more blogs on Cherrypy and Python to follow.

Thank you image

Explore Coding Ninjas Studio to find more exciting stuff. Happy Coding!

Live masterclass