Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda