Reputation: 94
I am building an SPA on Mongoose, Node, Backbone stack and using Handlebars. A user signs up for one or more courses. Then, user can go to his list of courses and cancel if he chooses. The API works, I can remove the courses from the database making an ajax call to the specific url from the console. The problem is I need the ajax call to take the variable from the handlebars template. How do I capture the {{_id}} from my handlebars template and pass it into an AJAX delete request that is outside the template?
template: Handlebars.compile(
'<h4>{{local.petname}} is a busy beast!</h4>'+
'<h2>Upcoming Courses: </h2>' +
'<ul>'+
'{{#each signup}}' +
'<li><h3>{{name}}</h3>{{coursDay}}{{time}}{{location}}</li>' +
'<a href="/test/signups/{{_id}}" data-id="{{_id}}"" class="btn btn-danger confirm-delete">Remove Course</a><br/><br/>' +
'<li>{{_id}}</li>'+
'{{/each}}'+
'</ul>'
),
Here is my ajax request; attrID returns the ObjectID of only the first item in the array
deleteItem: function(event) {
event.preventDefault();
var attrID = $('.btn-danger').data();
console.log(attrID);
jQuery.ajax({
url: "/test/signups/" + attrID,
type: "DELETE",
success: function (data, textStatus, jqXHR) {
console.log("Post response:");
console.dir(data);
console.log(textStatus);
console.dir(jqXHR);
}
});
}
Upvotes: 0
Views: 713
Reputation: 4033
I'm a little unsure where you want to call your deleteItem()
function, but the issue is with the jQuery selector:
$('.btn-danger')
selects all your links. You get them back in a jQuery wrapped list. The method data()
is then only applied to the first item of your list, thus resulting only in your first node. You should also provide the parameter 'id'
, otherwise you again will get an array.
Assuming you want all links to do the AJAX call, you can call:
$('.btn-danger').on('click', function(event) {
event.preventDefault();
var attrID = $(this).data('id');
console.log(attrID);
$.ajax({ ... });
});
Edit: replaced $(...).live()
(deprecated) with $(...).on()
.
There also is an issue with your handlebars template data-id="{{_id}}""
the second quotes should be removed.
Upvotes: 2