Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
How to callback `this` within ajax function

So I want to use this from an outer function within an ajax success function. I tried to apply these solutions but somehow I can't bring it to work.

// Submit vote on submit
$('.vote-choice-div').on('click', function(event){
    event.preventDefault();

    // bind the clicked object
    this.submit_vote.bind(this);    // so I have to bind the element to use it in the ajax function?

    // fire ajax
    submit_vote(this.id, this);

});
// AJAX for posting
function submit_vote(vote) {

    $.ajax({
            url : "submit-vote/",
            headers: {'X-CSRFToken': csrftoken}, 
            type : "POST",
            data : { vote : vote }, 

            success : function(data) {
                 if(data.status === 1){
                    
                     console.log(this)   // can't access the initial clicked element
                 }

Uncaught TypeError: Cannot read properties of undefined (reading 'bind')

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You have two problems (and a pointless argument).

  1. submit_vote is a global, not a property of the element. To access it, you don't use this.
  2. bind returns a new function. It doesn't mutate the existing one
  3. submit_vote only accepts one argument

So:

const localSubmitVote = submit_vote.bind(this)
localSubmitVote(this.id);

However… bind is only useful if you are going to store a function so you can pass it around or use it multiple times.

You aren't doing that, you're only calling it once, so use call

submit_vote.call(this, this.id);

However… submit_vote isn't a method. It isn't sensible to design it to use this in the first place. So the better approach here is to redesign it to just use the second argument that you were passing before.

function submit_vote(vote, element) {
  $.ajax({
    // ...
    success: function(data) {
      if (data.status === 1) {
        console.log(element);
      }
    }
  });
}

and

submit_vote(this.id, this)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda