Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!