Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load external page using ajax

Tags:

jquery

ajax

i have a link button that supposed to link to another page. The content of that page should be displayed to the current page. I'm using the bootstrap framework, however the function I created doesn't seem to work.

here's my code;

<a href="" id="reslink">link1</a>

<div class="span8" id="maincont"></div>

javascript;

$('#reslink').click(function(){
    $.ajax({
        type: "GET",
        url: "sample.html",
        data: { },
        success: function(data){
            $('#maincont').html(data);
        }
    });

});
like image 403
cfz Avatar asked Feb 18 '23 04:02

cfz


2 Answers

You have following ways.

First

use html as below,.

<a href="Javascript:void(0);" id="reslink">link1</a>

Javascript:void(0); work as return false from script.

Second

Do not change anything in html code but make below change in jQuery code.

$('#reslink').click(function(e){
    e.preventDefault();
    $.ajax({
        type: "GET",
        url: "sample.html",
        data: { },
        success: function(data){
            $('#maincont').html(data);
        }
    });
});

e.preventDefault(); prevent the default behavior of the HTML so you can execute your code.

like image 88
Dipesh Parmar Avatar answered Feb 27 '23 06:02

Dipesh Parmar


Maybe load() would be a better choice for you?

$("#reslink").click(function() {
    $("#maincont").load("sample.html");
});

Be mindful that loading content in this way could potentially break History and Favorites.

like image 32
SomeShinyObject Avatar answered Feb 27 '23 08:02

SomeShinyObject