Connecting a button's action to a specific element in an array using AJAX and Firebase

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!

Answer №1

The issue here arises from iterating through the entire list and assigning them to a global variable. This results in a lack of randomness as it simply selects the last item in the list, which is the final one assigned to the global variable.

Consider using jQuery instead of creating your own DOM events, and implementing a closure to access the video title.

function saveToDatabase(dataTitle) { 
 ref.push({
    title: dataTitle
  });  
}

$.ajax({
  type : 'GET',
  url : url,
  dataType : "jsonp",
  cache: false,
  success : function(data) {
    console.debug(data); // Note that console.debug may not be supported in all versions of IE
    buildVideoList(data.response.items);
  }
});

function buildVideoList(vids) {
  $.each(vids, function(vid) {
    var $img = $('<img></img>');
    $img.attr('src', sanitize(vid.title));

    var $button = $('<button class="btn">Save</button>');
    $button.click(saveToDatabase.bind(null, vid.title));

    $('<div class="tile"></div>')
      .append($img)
      .append($button)
      .appendTo('#content');
  });
}

// The following sanitization function may need improvement for better efficiency
function sanitize(url) {
  return url.replace(/[<>'"]/, '');
}

Answer №2

Instead of passing the index directly to the function, I decided to store it in a global array for easy access. Surprisingly, this method seems to be working without any issues. Is there any downside to doing it this way?

var vids = []; //global 

function foo() {
 $.ajax({
          type : 'GET',
          url : url,
            dataType : "jsonp",
            cache: false,
         success : function(data){
         console.debug(data);
         vids = data.response.items;

      for(var i in vids) {

        ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";

        $('#content').append( ncode )
} //end ajax function

function saveToDatabase(i) { 
 ref.push({
    title: vids[i].title
  });  
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to generate a button that randomly chooses links within the webpage

Looking for help with JavaScript to select a link when a button is clicked on the page? Check out my code and let me know what I'm doing wrong. For the full code, visit: here HTML <!doctype html> <html lang="it" xmlns="http:/ ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Prohibited Nested Attributes in Embedded Mongoid Document when Using AJAX

I'm facing an issue while attempting to submit a document and an embedded document through an Ajax call. I keep encountering an "Unpermitted parameter" exception. This is how my model is defined: class UserForecast ... embeds_many :time_entries ...

Encountering issues when trying to incorporate SASS and CSS libraries in NextJS

I have been attempting to integrate the wix-style-react plugin into my NextJS project, but I am encountering difficulties when trying to build. According to their documentation, they utilize Stylable, SASS, and CSS Modules. After installing the plugin and ...

"Troubleshooting CSS styling in React material-ui when using withStyles from an external

After reviewing this specific question, I still couldn't figure out how to make it work. The main goal is to keep the styles separate from the component file for a more organized setup. Everything runs smoothly without incorporating a theme. I atte ...

Having trouble importing a module or library in VueJS?

After setting up a slider library called Hooper in VueJS 3, I imported it locally like this: <template> <hooper> <slide>1</slide> <slide>1</slide> <slide>1</slide> <slide>1</slide&g ...

Keeping an HTML field constantly refreshed with dynamic content from Django

Imagine having two input fields along with an HTML paragraph displaying a Django value. Field A: <input ...> Field B: <input ...> <p>{{ sum }}</p> The goal is to have the sum update in real time, meaning that once both numbers ...

Encountering difficulty with displaying a 404 error using Cloud Functions on Firebase Hosting

I am currently facing an issue with handling a custom 404 error using Firebase Hosting and Functions. The code I have provided below works perfectly fine on localhost, but once deployed, Firebase Hosting returns a 500 error instead of the expected 404. ht ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

How can scripts communicate with one another through passing arguments?

"scripts": { "dev": "npm run development", "development": "run-something", .... When invoking my script, I use the following command: npm run dev This is a convenient shortcut that executes the standard command npm-run-development. Is there ...

Navigating Vue 3's slot attributes: A step-by-step guide

Currently, I am facing an issue with a Vue component named MediaVisual. This component contains a slot. The problem arises when attempting to retrieve the src attribute of the slot element that is passed in. Surprisingly, this.$slots.default shows up as u ...

Allow foreign characters with regex while excluding special symbols

While browsing, I came across this thread: Is there a regular expression to match non-English characters?. It provides a regex to remove foreign characters using the code snippet str = str.replace(/[^\x00-\x7F]+/g, "");. My goal is slightly diff ...

Get the contents inside the window.open using Javascript

First and foremost, I want to acknowledge that I understand the likelihood of this failing due to cross-domain restrictions - just seeking confirmation on that. Here's my approach: I have a window that I open using JavaScript. Subsequently, I make an ...

Ways to discreetly conceal forward and backward buttons in the v-pagination component of Vuetify

Is there a way to remove the previous and next buttons from v-pagination in Vuetify? Here's my code snippet- <v-pagination v-model="page" :length="pageCount" :total-visible="8" color="primary" /> ...

Modify the anchor text when a malfunction occurs upon clicking

Whenever I click on the link, I am able to retrieve the correct id, but the status changes for all posts instead of just the selected item. Below is the HTML code: <div th:each="p : ${posts}"> <div id="para"> <a style="float: right;" href= ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

Is there a way to redirect focus to an object with a lower z-index when working on overlaying a sequence of transparent divs on a map?

Is it possible to give focus to a parent div that contains a child div without hiding the child div? I am integrating the Google Maps API and need to overlay a grid of transparent divs for inserting information. However, with these divs on top of my map, ...

Is it possible to create a dynamic template in Angular using external sources?

My goal is to dynamically load HTML content using AJAX and then compile it, as it contains Angular directives. I have a specific class that includes methods for utilizing Angular outside the scope of an angular controller or directive: var AngularHelper ...

Encountering a parsererror with $.ajax while processing JSON that includes a new Date() object

After fetching JSON from a MongoDB database, I serialize it and send it back to the JavaScript client using a $.ajax call. Here is an example of the $.ajax call: function server_request(URL, httpMethod, dataObject) { var output = ""; var typeofD ...

Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...distfxcoreservermain.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or np ...