Arjun
Arjun

Reputation: 1279

FadeOut effect not calling AJAX function code

I'm learning some basic JQuery that appends Ajax queried data from a text file into a div element. The program doesn't work when the AJAX code is added and when the function is called from the fadeOut effect. Else the fadeOut works fine.

Am I supposed to code the AJAX in another file and link it? What is wrong in this code? Sorry if the title of the question isn't precise.

HTML

<html>    
    <head>
        <title>Help Me</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script src="test.js" type="text/javascript"></script>
    </head>

    <body>
        <div align="center" id = "div1" >
            <img src="pic1" width="200" height="200" alt="" id = "pic1" />
            <img src="pic2" width="200" height="200" alt="" id = "pic2" />
            <img src="pic3" width="200" height="200" alt="" id = "pic3" />
        </div>
        <div id = 'myDiv'></div>
    </body>
</html>

SCRIPT

$(document).ready(function() {
    $("#pic1").click(function() {
        $("#div1").fadeOut("slow", myFunction());
        $("#myDiv").fadeIn("slow");
    });

    $("#pic2").click(function() {
        $("#div1").fadeOut("slow");
    });

    $("#pic3").click(function() {
        $("#div1").fadeOut("slow");             
    }); 
});

var xmlhttp;
function loadXMLDoc(url, cfunc) {   
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

function myFunction() {
    loadXMLDoc("testfile.txt", function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    });
}

Upvotes: 1

Views: 260

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

You need to pass the reference of myFunction to the callback. Your current method is calling your function on page load instead. Try this:

$("#pic1").click(function() {
    $("#div1").fadeOut("slow", getData); // note: no () brackets
});

function getData() {
    $.get("testfile.txt", function(data) {
        $("#myDiv").html(data).fadeIn("slow");
    });
}

Upvotes: 1

Related Questions