makmani
makmani

Reputation: 91

Why am getting two ajax calls at same time?

I want to make a like on article , am using onclick event on a <div> where another function handles the request, here are the codes :

<div class="act">
    <respect class="respect">
      {% if new.voted_new(new.id) %}
        <div class="button_like" data-new="{{new.id}}" onclick="Unlike();">
            <div class="norespect" style="background: #2fcc71; border-color: #2fcc71;"></div>
        </div>
      {% else %}
        <div class="button_like" data-new="{{new.id}}"  onclick="Like();">
            <div class="norespect" style=""></div>
        </div>
      {% endif %}
        <p class='respectCount{{new.id}}'>{{new.respects}}</p>
    </respect>
    <views>
      <p class="views_count"><i class="fa fa-eye"></i> {{new.views}}</p>
    </views>
</div>

Here is JQuery code :

function Like(){
    $('.button_like, .respectCount').on('click', function(e){
      e.preventDefault();
      var new_id = $(this).attr('data-new');
      var p_result = $(this).attr('data-result');
      $.ajax({
        url: "/client/cat-{{g.current_directory}}/news/like/",
        type: 'post',
        cache: false,
        data: {
          new_id: new_id
        },
        success: function(data){
          $('p.respectCount'+new_id).text(data.result);
          console.log(data.result);
          $(this).fadeOut(500).fadeIn(500);
        },
        error: function(data){
          return false;
        }
      }).done(function(data){
        if (data){
          $('p.respectCount'+new_id).text(data.result);
          console.log(data.result);
          $(this).fadeOut(500).fadeIn(500);
        } else {
          return false;
        }
    });
});
}

The problem is that i have to click twice to make a like, also inside the console i got two ajax requests .

Please , any help ??

Upvotes: 0

Views: 82

Answers (2)

Adder
Adder

Reputation: 5868

The code inside function Like should be outside, in its own document.ready(function{...}). Like should be sending its own ajax request. Same probably for Unlike, which you haven't shown the code of.

Upvotes: 0

Satpal
Satpal

Reputation: 133403

As per your HTML, you have added inline click handler

<div class="button_like" data-new="{{new.id}}"  onclick="Like();">
</div>

And in the event handler, you are attaching unobtrusive event handler. Thus whenever button is clicked a new handler is attached.

Remove, ugly inline click handlers and just use unobtrusive event handlers

$(function () {
    $('.button_like, .respectCount').on('click', function (e) {
        //Your code
    });
});

Upvotes: 1

Related Questions