Reputation: 89
I'm trying to do is load an external html page then display the contents within a div when a button is clicked.
I get the alert message displaying the contents of the test.html, however when I try to display it within a div nothing happens.
The contents is just a div tag. I don't want to load the div tag just the text itself which does come up in the alert message.
Within a html file, I know I don't really need to use ajax for something so simple however if I can get this to work it will help me with future problems.
$.ajax({
type: "GET",
url: "test.html",
dataType: "text",
success : function(data) {
step1j = data;
alert(step1j); // WORKS
return step1j;
}
});
$("#step1").click(function() {
$("#texter").html(step1j);
});
Upvotes: 3
Views: 22956
Reputation: 707158
Ajax calls are asynchronous by default so what you have won't work. What I would suggest is using jQuery's .load()
which handles the entire loading into a div for you (jQuery reference info here).
$("#step1").click(function() {
$("#texter").load("test.html");
});
For this to work, the following must be true:
#step1
must exist already at the time you run this initial code (e.g. the DOM must already be loaded to install the .click()
handler. For example, you can't install a click handler from code in the <head>
tag because the page DOM has not yet loaded.#texter
must exist at the time of the click. Please make sure there is no misspelling there.Read this answer if you want to learn more about why you can't return data from an asynchronous Ajax call like you were trying to do. Asynchronous calls finish some indeterminate time later and thus the only reliable place to use their results is in the completion callback or in a function that you call from within the completion callback. In this case, .load()
is a higher level piece of jQuery functionality that makes this easier.
Upvotes: 4
Reputation: 8584
Try this:
$("#step1").click(function() {
$.ajax({
type: "GET",
url: "test.html",
dataType: "text",
success : function(data) {
$("#texter").html(data);
//step1j = data;
//alert(step1j); // WORKS
//return step1j;
}
});
});
Upvotes: 1