Sai Chand
Sai Chand

Reputation: 9

AJAX is calling multiple times even when i click once

My HTML CODE:

<div class="filter-section">
  {% for key, values in positions.items %}
    <h3>{{key}}</h3>
    {% for position in values %}
      <a id="view-job-{{position.id}}" style="cursor:pointer" onclick="getPositionInfo({{position.id}})" class="list-row">
       <span class="list-item">{{position.position_name}}</span>
      </a>
     {% endfor %}
    {% endfor %}
</div>

JS Code:

<script type="text/javascript">
    function getPositionInfo(id){
       var j_id = "#view-job-" + id;
       $(j_id).on('click', function(e) {
        e.preventDefault();
           $.ajax({
             url : '/apply_now/',
             type: 'POST',
             data:{
               job_id : id,
               csrfmiddlewaretoken: '{{ csrf_token }}'
              },
              success:function(data){
                alert(JSON.stringify(data));
              }
             });
        });
    }
</script>

Problem:
When on the first click nothing happens, but from the second click, it calls multiple times.
Example:
1st click -> no call
2nd click -> calls 2 times
3rd click -> calls 3 times
nth click -> calls n times

For 3rd click ajax called 5 times

Upvotes: 0

Views: 621

Answers (1)

Dean Elliott
Dean Elliott

Reputation: 1323

In the HTML you have defined an onclick="getPositionInfo({{position.id}})". This function getPositionInfo then adds another onclick to the <a> tag as soon as its called here $(j_id).on('click', function(e). So next time you click it, you are again adding another onclick and also calling the onclick you added previously.

Upvotes: 2

Related Questions