How to call ajax only once

I call a 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

 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 an ajax call only once? so when the content is loaded and the page does not refresh, so as not to load ajax? I tried to make booleans, but nothing, I support this because I call everytime function. Please give me an idea how to do this.

Thank you

+8
jquery ajax
source share
3 answers

If you want to do something at this event.

Determine when you have already uploaded 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. if 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."

link

+15
source share

Use the .one() function:

Attach a handler to the event for elements. A handler is executed no more than once for each element.

 <a href="#" title="" id="shownews"></a> 

I added the id attribute for the binding to make the binding easier, but you can 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(); }, }); }); }); 

event.preventDefault() also used to prevent the default action for the anchor

+11
source share
 <div id="header-button-news" class="header-button-info"> <a id="a_news" title=""></a> <div class="new">2</div> </div> 

In JS:

 $(function(){ $('a#a_news').one('click',showNews); }) 
+1
source share

All Articles