Reputation: 701
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
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
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
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
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