I am currently working on a project that involves making an AJAX request from a social API and then appending the results with a button inside the div. This button is meant to save the corresponding item in the array to my Firebase database.
For brevity, I have omitted most of the code related to the AJAX request. Here is the relevant snippet:
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
In addition, I have a function designed to save the 'title' of the object associated with the button that was appended:
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
However, a problem arises when the button is clicked as it posts a random title from within the array instead of the intended one. How can I ensure that the button's function binds correctly to the dataTitle? Any assistance would be greatly appreciated!