Reputation: 80
I am new to AJAX and wrote this code from some examples from internet and getting "Referenceerror: response is not defined"
My target: after clicking a button (search) the AJAX calls a servlet that takes select box and beside text box value as input and search the required data from Database and provide result in JSON format.
Then the JSON Object is processed and printed as table to the empty div present on the web page.
$(document).ready(function()
{
$("#search").click(function(event)
{
var selectedKey = $(".skey option:selected").val();
var insertValue = document.getElementById('svalue').value;
alert(selectedKey+":"+insertValue);
var url="SearchDetails?"+selectedKey+"="+insertValue
var request;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest()
}
else if(window.ActiveXObject)
{
request=new ActiveXObject("Microsoft.XMLHTTP")
}
try
{
request.onreadystatechange=printBands(response)
request.open("GET",url,true)
request.send()
}
catch(e)
{
alert("Unable to connect to server"+e)
}
});
});
function printBands(json)
{
if(request.readyState==4)
{
var mydata = eval(json);
var table = $.makeTable(mydata);
$(table).appendTo("#resultPrint");
}
$.makeTable = function (mydata)
{
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr>";
$(tblHeader).appendTo(table);
$.each(mydata, function (index, value)
{
var TableRow = "<tr>";
$.each(value, function (key, val)
{
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
$(table).append(TableRow);
});
return ($(table));
}
};
Upvotes: 0
Views: 1252
Reputation: 3321
change line
request.onreadystatechange=printBands(response)
to request.onreadystatechange=printBands;
. You need just pass a reference to function, not execute it in that place.
Upvotes: 1