Reputation: 657
Trying to DRY up some old javascript I wrote.
test()
function test() {
var output = function() {
return ajaxPost("test.php", "testvar=bananas");
}
document.getElementById("main").innerHTML = output;
}
ajaxPost()
function ajaxPost(file,stuff) {
var xmlhttp;
var actionFile = file;
var ajaxVars = stuff;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
return xmlhttp.responseText;
} else {
// Waiting...
}
}
xmlhttp.open("POST", actionFile, true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(ajaxVars);
}
The output that I am receiveing is this:
<div id="main">
function () { return ajaxPost("test.php", "testvar=bananas"); }
</div>
I can't figure out why it's sticking the function in the div instead of what the function is supposed to actually do. Any thoughts?
Upvotes: 1
Views: 2532
Reputation: 74046
You have to execute the function by adding ()
to it, else you receive the function body!
function test() {
var output = function() {
return ajaxPost("test.php", "testvar=bananas");
}
document.getElementById("main").innerHTML = output();
}
Furthermore you try to return a value from the AJAX call here
return xmlhttp.responseText;
This wont work as in an asynchronous call there is nothing that catches the returned value! You should call some kind of callback, which uses the returned value.
This would be a callback approach similar to your code:
function test( data ) {
document.getElementById("main").innerHTML = data;
}
function ajaxPost(file,stuff,cb) {
// ...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb( xmlhttp.responseText );
} else {
// Waiting...
}
}
// ...
}
// make the actual call
ajaxPost("test.php", "testvar=bananas", test);
Upvotes: 6