user1184100
user1184100

Reputation: 6894

Fetching a html page dynamically and animating it - jquery

I want to fetch a html page and display it with a fadeIn animation... But the fetching doesn't work and due to this even the animation

$(document).ready(function() {
var src;

    $.ajax({
        url: "pages/sample.html",
        success: function (data) { src=data },
        dataType: 'html'
     });

    console.log(src);   **// Throws undefined**

    //To animate
    $(function() {
        $('html')
            .hide()
            .html(src)
            .fadeIn(5000);
    });
});

Upvotes: 0

Views: 97

Answers (3)

apfelbox
apfelbox

Reputation: 2634

AJAX is a asynchronous operation, meaning that you cannot expect the result to be available at once, but some time in the future. jQuery provides the ability to use a callback, which is called, as soon as the result is available. You have to modify your code a little bit:

$(function() {

    $.ajax({
        url: "pages/sample.html",
        success: function (data) { ajaxDataArrived(data); },
        dataType: 'html'
     });

    function ajaxDataArrived (src) {
        console.log(src);
        $("html").hide().html(src).fadeIn(5000);
    }

});

Please note, that there is a specific function for loading HTML content in jQuery: .load(). It works slightly different than the code example above, since jQuery handles the callback for you:

$("html").load("pages/sample.html");

This will load and automatically insert the content, as soon as it's loaded. You can provide a callback for this function too, but it is called after the code is inserted. So this might not work in your case, since you want to hide the html before inserting it. I just wanted to add it for the sake of completeness.

Upvotes: 1

jogesh_pi
jogesh_pi

Reputation: 9782

Use .load() instead of ajax() something like:

$('#result').load('pages/sample.html', function() {
  //animation goes here
});

for more info visit .load()

Upvotes: 1

gdoron
gdoron

Reputation: 150313

ajax is an async operation, meaning it will return in the future.
Enter the code that uses the return value inside the success callback:

$.ajax({
    url: "pages/sample.html",
    success: function (data) { 
                 src=data ;
                 console.log(src);
            },
    dataType: 'html'
 });

Upvotes: 2

Related Questions