Manish Gupta
Manish Gupta

Reputation: 4666

how to pass multiple ajax calls in a single django view

I have a form with multiple button which is mapped to a django view. Like:

<form name="demo-form" method="POST" action="{% url 'internalManifest' %}">
    <button class="btn btn-success" name="start_manifest">Start Manifest</button>
    <button class="btn btn-success" name="close_manifest">Close Manifest</button>
</form>

The above two buttons call two different methods from models.py but i can do it from a single django view. Like:

Django view:

if request.method == 'POST' and 'start_manifest' in request.POST:
    call_function1()
if request.method == 'POST' and 'close_manifest' in request.POST:
    call_function2()

My question is, how to send two different ajax request like this to same view function based on name of button?

Lets say I have 2 ajax request. Both calls different method from models.py. I want to send the ajax call based on button name. like:

jQuery(document).ready(function($){
    $('[name="form_internal_manifest"]').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url : "/internalmanifest/",
            type : "POST",
            ...

jQuery(document).ready(function($){
    $('[name="form_internal_manifest"]').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url : "/internalmanifest/",
            type : "POST",
            ...

Upvotes: 2

Views: 3139

Answers (2)

CORTIZ
CORTIZ

Reputation: 101

Agree with @gtlambert but this can be made more concise as follows:

if request.method == 'POST':
    if request.POST['action'] == 'start_manifest':
        call_function1()
    elif request.POST['action'] == 'close_manifest':
        call_function2()

Upvotes: 0

gtlambert
gtlambert

Reputation: 11971

You could send some data in the AJAX request which will distinguish between the two functions:

jQuery(document).ready(function($){
    $('[name="form_internal_manifest"]').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url : "/internalmanifest/",
            type : "POST",
            data: {action: 'start_manifest'},
            ...

jQuery(document).ready(function($){
    $('[name="form_internal_manifest"]').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url : "/internalmanifest/",
            type : "POST",
            data: {action: 'close_manifest'},
            ...

The data you send will be available in the request.POST dictionary object, so you can condition on it as follows:

if request.method == 'POST' and request.POST['action'] == 'start_manifest':
    call_function1()
if request.method == 'POST' and request.POST['action'] == 'close_manifest':
    call_function2()

Upvotes: 6

Related Questions