1

I have this code:

$("a.ajax").on('click', function() {
    ajax_link();
});

function ajax_link() {
   $('#ajax_load').remove(); // Remove js
   $('#section').html('<?php echo $this->ajax_loading; ?>');
   setInterval( function() {
       $('#section').load($(this).attr('href')+'&ajax=true'); 
       return false;
   }, 1000);
}

But when I click the link it reloads the page instead of loading the content. Does anyone know why?

I added the rest of the code to make sure its not that.

Tepken Vannkorn
  • 9,648
  • 14
  • 61
  • 86
Jay
  • 68
  • 1
  • 10

3 Answers3

1

You need to prevent the default behavior of the anchor, which is causing the page to reload. You can do it via the preventDefault() method available in the event argument.

$("a.ajax").on('click', function(e){
       e.preventDefault();
      ajax_link.call(this);
});

Another issue is that inside the setInterval callback this represents the window and not the anchor you clicked on, so cache the this context to a variable and use it.

function ajax_link(){
var self = this; //Cache it here
setInterval(function(){
    $('#section').load(self.href +'&ajax=true'); 
        return false; //You dont need this.
     },1000);
}

Or Just bind it:

$("a.ajax").on('click', ajax_link);


function ajax_link(e){
var self = this; //Cache it here
e.preventDefault();
setTimeout(function(){ //Use setTimeout
    $('#section').load(self.href +'&ajax=true'); 
        return false; //You dont need this.
     },1000);
}
PSL
  • 123,204
  • 21
  • 253
  • 243
  • This still isn't working. The `#section` just goes blank now. – Jay Oct 15 '13 at 01:49
  • Seems to still not load the page. Do you need more info from me? If so what? Thanks mate – Jay Oct 15 '13 at 01:54
  • @Jay It has to Unless you are accesing url from another domain. Network console is your friend. Check for any error there. – PSL Oct 15 '13 at 01:57
  • hehe Its working, thanks so much. But the setinterval is making the page load every secdon, best remove that lol. But how would I get my loading image to display for at least 1-2 seconds? – Jay Oct 15 '13 at 01:59
  • @Jay Use setTimeout instead of setInterval. See my answer update. – PSL Oct 15 '13 at 02:00
0

Use e.preventDefault()

the default action of the event will not be triggered.

$("a.ajax").on('click', function (e) {
    e.preventDefault();
    ajax_link();
});

or you can modify your HTML

<a class="ajax" href="javascript:void(0)">Load ajax</a>
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

If you are using the latest version of jQuery, you may return false from your click event handler. Returning false will preventDefault() and stopPropagation(). StackOverflow has a reference to this... event.preventDefault() vs. return false

Community
  • 1
  • 1
Dennis Flagg
  • 664
  • 6
  • 12