Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery $get / $ajax not working in all browsers

I have code like below:

$('a.load-more').on("click",function(){
    $.get($('a.load-more').attr('href'), function(data) {
   $(".next-page").remove();
   $('.block-grid').append(data);
   event.preventDefault();
});

The html:

<li class="next-page">
<a href="http://example.com/ajax_all/" class="load-more">Load More →</a>
</li>

Which as you can see, takes the url of the ajax content from the .load-more element, passes it to the $get method which then pulls in the content and appends it into the current page.

The odd thing is though, this is working in Chrome but not Firefox or Safari and there are no js errors in the inspectors for those browsers.

Instead of pulling the content in using ajax, it just goes to the url http://example.com/ajax_all/ and displays the content of that.

I'm stumped as to why it would work in Chrome and not Safari or firefox.

like image 664
John Avatar asked Dec 21 '12 15:12

John


2 Answers

You script is invalid, or pasted wrong

$('a.load-more').on("click", function () {
    $.get($('a.load-more').attr('href'), function (data) {
        $(".next-page").remove();
        $('.block-grid').append(data);
        event.preventDefault();

});

After fixing that it shows that your event.preventDefault(); is happening inside of the get() which is asynchronous.

$('a.load-more').on("click", function () {
   $.get($('a.load-more').attr('href'), function (data) {
      $(".next-page").remove();
      $('.block-grid').append(data);
      event.preventDefault();
   });
});

Placing the preventDefault outside of the call back should fix your problem.

$('a.load-more').on("click", function (e) {
    $.get($('a.load-more').attr('href'), function (data) {
        $(".next-page").remove();
        $('.block-grid').append(data);

    });
    e.preventDefault();
});
like image 53
Mark Coleman Avatar answered Nov 19 '22 09:11

Mark Coleman


Your problem is the word event, it must be in the parameters of click callback.

Try that:

$('a.load-more').on("click", function(e){
    e.preventDefault();
    $.get($('a.load-more').attr('href'), function(data) {
        $(".next-page").remove();
        $('.block-grid').append(data);
    });
});
like image 29
Renan Cunha Avatar answered Nov 19 '22 09:11

Renan Cunha