steph
steph

Reputation: 701

Sending data on click

I'm using Ajax (along with Django) to perform some action on button click. Before I even get to the view, I am unable to pass data to the javascript function. What is going wrong? How can I pass the button's ID data to the function? I get the message that my request_data is Undefined.

template.html

<button class="btn-green" onclick="request_access()" id="{{ data }}">Join Group</button>

javascript.js

function request_access(){
    console.log("button clicked");
    var request_data = $(this).attr('id');
    console.log("data: " + request_data);
    $.post({
        url: "request_access/",
        data : { request_data: request_data},
        success : function(json) {
            $("#request-access").hide();
            console.log("requested access complete");
        }
    })
}

Upvotes: 1

Views: 14987

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Syntax of $.post is not correct, also pass the this instance in onclick handler. Inside the function this refers to window object not the clicked DOM element.

HTML

<button class="btn-green" onclick="request_access(this)" id="{{ data }}">Join Group</button>

jQuery

function request_access($this){
    console.log("button clicked");
    var request_data = $this.id;
    console.log("data: " + request_data)
    $.post( "request_access",{ request_data: request_data},function(json) {
         $("#request-access").hide();
         console.log("requested access complete");
    })
}

Upvotes: 2

jperelli
jperelli

Reputation: 7197

Bind the onclick event using jquery also, like this:

jQuery(function($){
    $('.btn-green').on('click', function(e) {
          var request_data = $(this).attr('id');
          $.post .......
          .....
    })
})

and get rid of the onclick="request_access()" in html

ALSO: Maybe you haven't pass "data" to the django template. Can you show us the generated html AND the django view function?

Upvotes: 1

shafiq.rst
shafiq.rst

Reputation: 1296

<button class="btn-green" onclick="request_access('{{ data }}')" id="{{ data }}">Join Group</button>

javascript.js

function request_access(id){

    var request_data =id;
    console.log("data: " + request_data);
    $.post({
        url: "request_access",
        data : { request_data: request_data},
        success : function(json) {
            $("#request-access").hide();
            console.log("requested access complete");
        }
    })
}

Upvotes: 0

Joshua K
Joshua K

Reputation: 2537

this is the window object. don't use eventhandlers within html-tags. this is one reason. split your javascript code and your html structure.

if you cannot do that: use the window.event to detect the event-owner.

Upvotes: 1

Related Questions