I am making an AJAX call using jQuery to an .ascx control’s method in the code behind to get a list of business objects:
C# Code:
if (Request.Headers["X-OFFICIAL-REQUEST"] == "TRUE") ReturnList(Request.Params[1]);
protected void ReturnList(string param)
{
Response.Write(GetBusinesses(param));
Response.Flush();
try {
Response.Close();
}
catch { }
Response.End();
return;
}
private string GetBusinesses(string classificationName)
{
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = null;
if (!string.IsNullOrEmpty(classificationName))
{
dSourse = BusinessesDBService.Instance.GetLatestListingsUpdates(classificationName).ToList();
jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
}
return jSearializer.Serialize(dSourse);
}
jQuery Code:
window.jQuery.ajax({
type: "POST",
async: false,
url: location.href,
dataType: "json",
data: ({ 'FUNCTION': 'ReturnList', 'param0': classificationName.toLowerCase() }),
success: function (data) {
data = eval(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-OFFICIAL-REQUEST", "TRUE"); //Used to ID as a AJAX Request
},
complete: function (XMLHttpRequest, textStatus) {
//build HTML
var tablestring = '<table ><tr><td>UsreID" + "</td><td>UserName</td></tr>';
for (var i = 0, len = data.length; i < len; ++i) {
tablestring = tablestring + "<tr>";
tablestring = tablestring + "<td>" +
data[i].BusinessID + "</td>";
tablestring = tablestring + "<td>" +
data[i].BusinessName + "</td>";
tablestring = tablestring + "</tr>";
}
tablestring = tablestring + "</table>";
var divResult = document.getElementById("divAjax");
divResult.innerHTML = tablestring;
}
});
The http call is executed fine and the collection is serialized and returned with the response however I have a few problems here. The main one is that the HTML is not being created – I am not able to capture the string returned. The string below shows up in the Firebug script window after the call is complete
[{“BusinessID”:6549,”BusinessName”:”Ivory Store”,”IsMain”:true}, {“BusinessID”:16565,”BusinessName”:”Classic Nails”,”IsMain”},{“BusinessID”:5877,”BusinessName”:”Visible Changes Hair”,”IsMain”:true}]
Also in the Firebug I have noticed that string in XMLHttpRequest response object and the error message is “JSON is not valid” Any suggetions? Thank you very much.
For some reason the code-behind C# parser code below was not appending “]” to the end of the string so I had to append it manually – it worked!!! Thank you.