Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ajax only once

Tags:

jquery

ajax

I call function from this code :

    <div id="header-button-news" class="header-button-info">
        <a href="javascript:;" title="Новости" onclick="showNews()"></a>
        <div class="new">2</div>
    </div>

My function is

function showNews()
{          
        //other js which show block 

        jQuery("#loader").show();


        //ajax which load content to block
        jQuery.ajax({
            type: "GET",
            url: link,
            dataType: "html",
            success: function(data) {
                jQuery('#top-info-news').html(data);   
            },
            complete: function(){
                jQuery('#loader').hide();
            },
        });
}

How can I make only once ajax call? so when content is loaded and page was not refresed not to load ajax? I tried to do boolean variables but nothing, I suppouse it is because I call everytime function. Please give me an idea how to do.

thank you

like image 259
Viktors Avatar asked Jul 31 '12 11:07

Viktors


2 Answers

When you want to do something on that event.

Identify when you have already loaded your data.

var loaded = false;

function showNews() {
    //other js which show block 

    jQuery("#loader").show();


    if(loaded) return;

    //ajax which load content to block
    jQuery.ajax({
        type: "GET",
        url: link,
        dataType: "html",
        success: function(data) {
            jQuery('#top-info-news').html(data);   
        },
        complete: function(){
            jQuery('#loader').hide();
        },
    });

    loaded = true;
}

Or use one. when you want to call it once.

<a href="javascript:;" title="Новости" onclick="showNews()" class="showNews"></a>

jQuery('.showNews').one('click', function() {
    // your code
});

"Attach a handler to an event for the elements. The handler is executed at most once per element."

reference

like image 76
Ricardo Alvaro Lohmann Avatar answered Oct 23 '22 08:10

Ricardo Alvaro Lohmann


Use the .one() function :

Attach a handler to an event for the elements. The handler is executed at most once per element.

<a href="#" title="Новости" id="shownews"></a>

I have added an id attribute to the anchor to allow an easier bind, but you could use $("#header-button-news a").one

$(document).ready(function () {
  $('#shownews').one('click', function (evt) {

    evt.preventDefault(); // prevent default click action

    jQuery("#loader").show();
    //ajax which load content to block
    jQuery.ajax({
      type: "GET",
      url: link,
      dataType: "html",
      success: function (data) {
        jQuery('#top-info-news').html(data);
      },
      complete: function () {
        jQuery('#loader').hide();
      },
    });
  });
});

Also used event.preventDefault() to prevent the default action on the anchor from being followed

like image 22
Manse Avatar answered Oct 23 '22 08:10

Manse