Git Product home page Git Product logo

django-ajax's Introduction

django-ajax

Fast and easy AJAX libraries for django projects.

Build Status

PYPI Package

PYPI Download

PYPI Versions

PYPI Status

PYPI License

Requirements

Installation

Install django-ajax in your python environment

1- Download and install package:

$ pip install djangoajax

Through Github:

pip install -e git://github.com/yceruto/django-ajax#egg=djangoajax

or simply with:

$ python setup.py install

2- Add 'django_ajax' into the INSTALLED_APPS list.

3- Read usage section and enjoy its advantages!

Usage

@ajax Decorator

from django_ajax.decorators import ajax

@ajax
def my_view(request)
    do_something()

When nothing is returned as result of view then returns (JSON format):

{"status": 200, "statusText": "OK", "content ": null}

Sending custom data in the response

@ajax
def my_view(request):
    c = 2 + 3
    return {'result': c}

The result is send to the browser in the following way (JSON format)

{"status": 200, "statusText": "OK", "content": {"result": 5}}

Combining with others decorators

from django.contrib.auth.decorators import login_required
from django_ajax.decorators import ajax

@ajax
@login_required
def my_view(request):
    # if the request.user is anonymous then this view not proceed 
    return {'user_id': request.user.id}

The JSON response:

{"status": 302, "statusText": "FOUND", "content": "/login"}

Template response

from django.shortcuts import render
from django_ajax.decorators import ajax

@ajax
def my_view(request):
    return render(request, 'home.html')

The JSON response:

{"status": 200, "statusText": "OK", "content": "<html>...</html>"}

Catch exceptions

@ajax
def my_view(request):
    a = 23 / 0  # this line throws an exception
    return a

The JSON response:

{"status": 500, "statusText": "INTERNAL SERVER ERROR", "content": "integer division or modulo by zero"}

AJAXMiddleware

If you use AJAX quite frequently in your project, we suggest using the AJAXMiddleware described below.

Add django_ajax.middleware.AJAXMiddleware into the MIDDLEWARE_CLASSES list in settings.py.

All your responses will be converted to JSON if the request was made by AJAX, otherwise is return a HttpResponse.

Caution

If you use this middleware cannot use @ajax decorator.

AJAXMixin for class-based views

AJAXMixin is an object that calls the AJAX decorator.

from django.views.generic import TemplateView
from django_ajax.mixin import AJAXMixin

class SimpleView(AJAXMixin, TemplateView):
    template_name = 'home.html'

The JSON response:

{"status": 200, "statusText": "OK", "content": "<html>...</html>"}

AJAX on client side

Include jquery.ajax.min.js into base.html template:

<script type="text/javascript" src="{% static 'django_ajax/js/jquery.ajax.min.js' %}"></script>

Call to AJAX request using the ajaxPost or ajaxGet functions:

<script type="text/javascript">
    ajaxPost('/save', {'foo': 'bar'}, function(content){
        //onSuccess
        alert(content);
    })
</script>

or

<script type="text/javascript">
    ajaxGet('/', function(content){
        //onSuccess
        alert(content);
    })
</script>

If the response is not successful, it's shown an alert with the message appropriated.

AJAX plugin (Based on eldarion-ajax)

Include jquery.ajax-plugin.min.js into base.html template:

<script type="text/javascript" src="{% static 'django_ajax/js/jquery.ajax-plugin.min.js' %}"></script>

In this moment any tag with the attribute data-ajax will be controlled by ajax plugin. Each request is sent using AJAX and the response will be handle on JSON format.

The value of the attribute data-success will be used as callback function if the request is successful. This function is called with an argument that represent the content response:

<a href="/hello-world/" class="btn btn-primary" data-ajax="true" data-success="processResponse">Show Alert</a>

Where "processResponse" in this case is a callback function:

<script type="text/javascript">
     function processResponse(content) {
         do_something(content);
     }
 </script>

Process fragments

Inspired on eldarion-ajax the data received by the names 'fragments', 'inner-fragments', 'append-fragments' or 'prepend-fragments' will be processed by default, unless you pass in the request the option "process-fragments" equal false. Here's an example:

@ajax
def fragments_view(request):
    data = {
        'fragments': {
            '#id1': 'replace element with this content1'
        },
        'inner-fragments': {
            '#id2': 'replace inner content'
        },
        'append-fragments': {
            '.class1': 'append this content'
        },
        'prepend-fragments': {
            '.class2': 'prepend this content'
        }
    }
    return data

These data are sent in response:

{"status": 200, "statusText": "OK", "content": {
        "fragments": {"#id1": "replace element with this content1"},
        "inner-fragments": {"#id2": "replace inner content"},
        "append-fragments": {".class1": "append this content"},
        "prepend-fragments": {".class2": "prepend this content"}
    }}

Then, using AJAX (ajax, ajaxPost or ajaxGet) functions these fragments to be processed automatically before calling to success function.

<script type="text/javascript">
     function fragments() {
         ajaxGet('/fragments-view-url', function(content){
             alert('The fragments was processed successfully!');
         });
     }
 </script>

If you do not want to process the fragments never, modify the AJAX configuration that comes by default:

<script type="text/javascript">
    ajax.DEFAULTS["process-fragments"] = false; //true by default
</script>

or as option on the request:

<script type="text/javascript">
    function fragments() {
        ajaxGet('/fragments-view-url', function(content){
            do_something_with(content.fragments);
        }, {"process-fragments": false});
    }
</script>

Enjoy!

django-ajax's People

Contributors

b3ni avatar furious-luke avatar kavdev avatar luisza avatar quazer avatar yasminvc avatar yceruto avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.