How to make an AJAX call with CherryPy and jQuery

Want to send a JSON AJAX request to a CherryPy back-end using jQuery? Here's a quick example.

The JavaScript

Let's create a sample request that will send JSON data to the back-end, to see if a username exists in the system:

$(document).ready(function() {

    //put together a sample request, to find out if a username is taken
    var requestData = {
        username: 'jackie'

    //the URL where we'll send the AJAX request
    var url = '/Home/UsernameExists';

    //make the AJAX call over POST
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(requestData),
        url: url,
        error:function () {
            alert('Sorry, an error occurred. Please try again later.');
        success: function(response) {
            alert(response.exists); //this will alert "true" if the user exists

The Python

The UsernameExists method below is where the JSON request is read, and where the JSON response is returned. The other method just renders the page from which the request occurs (see the CherryPy MVC article for context).

import cherrypy
from controllers.base import BaseController

class HomeController(BaseController):
    def index(self):
        return self.render_template('home/index.html')

    def UsernameExists(self):
        json_obj = cherrypy.request.json
        usernames = ['bruce', 'lee', 'jackie', 'chan']
        return {"exists": json_obj['username'] in usernames}

Helpful Links

CherryPy JSON Tools Documentation
How to receive JSON in a POST Request


Leave a comment

What color are brown eyes? (spam prevention)
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.