responseXML from XMLHttpRequest Object doesn't work - asp.net

Please, can somebody help me by letting me know what I am doing wrong. I am returning an XML file dynamically using ASP.NET. Here is my code in VB in ASP.NET
<%# Page Language="VB" ContentType="text/xml"%>
<%# Import namespace="System.Xml"%>
<%# Import namespace="System.Text"%>
Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
Dim writer As XmlTextWriter
writer = New XmlTextWriter(Response.OutputStream, Encoding.UTF8)
writer.WriteStartDocument()
writer.WriteStartElement("options")
writer.WriteElementString("option", "Rojo")
writer.WriteElementString("option", "Verde")
writer.WriteEndElement()
writer.WriteEndDocument()
writer.Close()
End Sub
Then, using AJAX I am trying to get the XML file with responseXML but nothing happens. responseXML doesn't retrieve the XML. Any help would be greatly appreciated. I use alerts to see if the code is returning something from the responseXML. responseXML returns null.
This is my javacript code where I have used the responseXML. Thank you.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Using Ajax and XML</title>
<script language="javascript">
var XMLHttpRequestObject = false;
//var xmlDocument;
var options;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
/****Indicates the Firefox browser that the returned data will have a content type/
if (XMLHttpRequestObject.overrideMimeType) {
XMLHttpRequestObject.overrideMimeType("text/xml");
}
/******************************************************/
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getoptions1()
{
if (XMLHttpRequestObject)
{
XMLHttpRequestObject.open("GET", "options1.aspx", true);
//XMLHttpRequestObject.setRequestHeader("Content-Type", "text/xml");
XMLHttpRequestObject.onreadystatechange=function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
var xmlDocument = XMLHttpRequestObject.responseXML;
alert(xmlDocument);
options = xmlDocument.documentElement.getElementsByTagName("option");
alert(options.length);
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<h1>Using Ajax and XML</h1>
<form>
<select size="1" id="optionList" onchange="setoption()">
<option>Select a scheme</option>
<option>Select a scheme</option>
</select>
<input type="button" value="Use color scheme 1" onclick="getoptions1()">
<input type="button" value="Use color scheme 2" onclick="getoptions2()">
</form>
<div id="targetDiv">Set the color of this text</div>
</body>
</html>

I found what the problem was. Instead of using an aspx file to output my XML, I used a ashx file. This is the ashx file created
<%# WebHandler Language="VB" Class="options1" %>
Imports System
Imports System.Web
Imports System.Xml
Public Class options1 : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim doc As XmlDocument
Dim str As String = ""
Dim options() As String = {"red", "green", "blue"}
Dim arrayItem As String
For Each arrayItem In options
str = str + "<option>" + arrayItem + "</option>"
Next
doc = New XmlDocument
doc.LoadXml("<options>" + str + "</options>") '("<options><option>red</option></options>")
context.Response.ContentType = "text/xml"
context.Response.ContentEncoding = Encoding.UTF8
context.Response.Cache.SetAllowResponseInBrowserHistory(True)
doc.Save(context.Response.Output)
End Sub
Then in the javascript I called the ashx file in the open method of the XMLHttpRequest. Here is the code.
<script language="javascript">
var XMLHttpRequestObject = false;
var xmlDocument;
var options;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
if (XMLHttpRequestObject.overrideMimeType) {
XMLHttpRequestObject.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getoptions1()
{
if (XMLHttpRequestObject)
{
XMLHttpRequestObject.open("GET", "options1.ashx", true);
XMLHttpRequestObject.onreadystatechange=function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
xmlDocument = XMLHttpRequestObject.responseXML;
options = xmlDocument.getElementsByTagName("option");
alert(options.length);
}
}
XMLHttpRequestObject.send(null);
}
}

Related

Microsoft Translator API v3, ASP.NET VB.NET

I am trying to call on the MS Translator API through an ASP.NET function to translate various strings from a database.
All examples from MS are given in C# so I throw into a converter and go from there.
From my searching I'm pretty sure this is an async/await issue. I have also tried setting strString to different things at different times but it throws the same error as if I'm not awaiting properly.
From the aspx page I have this:
<%# functions.translate(Eval("Description").ToString) %>
Description is a field from a database and shows properly if not passed to the translate function. I have other functions that I call to do various things and work properly.
In my functions.vb I have:
Public Class TranslationResult
Public Property Translations As Translation()
End Class
Public Class Translation
Public Property Text As String
Public Property [To] As String
End Class
Public Class functions
Public Shared Async Function translate(strString As String) As Task(Of String)
Dim host As String = "https://api.cognitive.microsofttranslator.com"
Dim route As String = "/translate?api-version=3.0&to=fr"
Dim key As String = "0000000000000000000000000"
Dim body As Object() = New Object() {New With {Key .Text = strString}}
Dim requestBody = JsonConvert.SerializeObject(body)
Using client = New HttpClient()
Using request = New HttpRequestMessage()
request.Method = HttpMethod.Post
request.RequestUri = New Uri(host & route)
request.Content = New StringContent(requestBody, Encoding.UTF8, "application/json")
request.Headers.Add("Ocp-Apim-Subscription-Key", key)
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)
Dim result As String = Await response.Content.ReadAsStringAsync()
Dim deserializedOutput As TranslationResult() = JsonConvert.DeserializeObject(Of TranslationResult())(result)
For Each o As TranslationResult In deserializedOutput
For Each t As Translation In o.Translations
strString = t.Text
Next
Next
End Using
End Using
Return strString
End Function
The error I'm getting is on the web page showing System.Threading.Tasks.Task`1[System.String] when I'm expecting a translated string.
I used your code as base and got it working. Just using a simple Webform.
Didn't change anything in the code, but I was prompted to add
Imports System.Net.Http
By Visual studio 2019
The final entire webform codebehind vb.aspx looks like this:
Imports System.Net.Http
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Public Class microsoftTranslator
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dim translatedText = functions.translate( "This is going to be one, two, three in french").Result
End Sub
Public Class TranslationResult
Public Property Translations As Translation()
End Class
Public Class Translation
Public Property Text As String
Public Property [To] As String
End Class
Public Class functions
Public Shared Async Function translate(strString As String) As Task(Of String)
Dim host As String = "https://api.cognitive.microsofttranslator.com"
Dim route As String = "/translate?api-version=3.0&to=fr"
Dim key As String = "0000000000000000000000000"
Dim body As Object() = New Object() {New With {Key .Text = strString}}
Dim requestBody = JsonConvert.SerializeObject(body)
Using client = New HttpClient()
Using request = New HttpRequestMessage()
request.Method = HttpMethod.Post
request.RequestUri = New Uri(host & route)
request.Content = New StringContent(requestBody, Encoding.UTF8, "application/json")
request.Headers.Add("Ocp-Apim-Subscription-Key", key)
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)
Dim result As String = Await response.Content.ReadAsStringAsync()
Dim deserializedOutput As TranslationResult() = JsonConvert.DeserializeObject(Of TranslationResult())(result)
For Each o As TranslationResult In deserializedOutput
For Each t As Translation In o.Translations
strString = t.Text
Next
Next
End Using
End Using
Return strString
End Function
end class
End Class
To make it wait for the async result look at the .result property
<%# Page Language="VB" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Net" %>
<!DOCTYPE html>
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim APIUrlToSend As String = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de"
Dim MyMainRequest As HttpWebRequest = CType(HttpWebRequest.Create(APIUrlToSend), HttpWebRequest)
MyMainRequest.Headers.Add("Ocp-Apim-Subscription-Key", "YOUR API CODE")
MyMainRequest.ContentType = "application/json; charset=utf-8"
MyMainRequest.Method = "POST"
' Send request
Dim MyJavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim TextToTranslate As String = MyJavaScriptSerializer.Serialize("Text to translate")
Dim MyMainRequestBody As String = "[{ Text: " & TextToTranslate & " }]"
Dim MyMainRequestBytesData As Byte() = Encoding.UTF8.GetBytes(MyMainRequestBody)
MyMainRequest.ContentLength = MyMainRequestBytesData.Length
Using RequestWriteStream = MyMainRequest.GetRequestStream()
RequestWriteStream.Write(MyMainRequestBytesData, 0, MyMainRequestBytesData.Length)
End Using
Dim MyFinalResponse As HttpWebResponse = MyMainRequest.GetResponse()
Dim MyFinalResponseStream As Stream = MyFinalResponse.GetResponseStream
Dim MyFinalResponseStreamReader As New StreamReader(MyFinalResponseStream, Encoding.GetEncoding("utf-8"))
Page.Response.Write(MyFinalResponseStreamReader.ReadToEnd())
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>

Uploading image to ASP.NET site with avalible content-type

I currently have a web service set up to upload and save a file (.png image) to my website using the following code:
[WebMethod]
public string SaveDocument(byte[] docbinaryarray, string docname)
{
string strdocPath;
string docDirPath = Server.MapPath("\\") + uploadDir;
strdocPath = docDirPath + docname;
if (!Directory.Exists(docDirPath))
Directory.CreateDirectory(docDirPath);
FileStream objfilestream = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
objfilestream.Close();
return "http:\\\\example.com\\" + uploadDir + docname;
}
This code works fine, however when I access the image via the url I am not getting a content type that matches the png file (image/png). Is it possible to associate the content type when you upload a file so that when you visit the url (example.com/myimage.png) it returns the image with the image/png content type? Or do I need to somehow dynamically create webpages with the content type that link to these links?
EDIT:
The goal is to use this with a 3rd party API that needs to do a GET request and needs to know the content-type, right now it specifies as invalid.
I think that something is not configired well in a your web server that blocks files or you pass wrong file name to this web service method.
I tested it and wrote simple implementation and all worked well. ASP.NET page uploads image to web service, web service returns a URL to uploaded image, page displays the image through Image1 control.
My simple implementation:
Default.aspx:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick" />
<asp:Image ID="Image1" runat="server" />
</form>
</body>
</html>
Default.aspx.cs:
namespace TestAspNetWebApp
{
using System.IO;
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_OnClick(object sender, EventArgs e)
{
string appPath = Request.PhysicalApplicationPath + "\\uploads\\";
if (!Directory.Exists(appPath))
Directory.CreateDirectory(appPath);
if (FileUpload1.HasFile)
{
string savePath = appPath + Server.HtmlEncode(FileUpload1.FileName);
FileUpload1.SaveAs(savePath);
using (var objfilestream = new FileStream(savePath, FileMode.Open, FileAccess.Read))
{
var len = (int) objfilestream.Length;
var mybytearray = new Byte[len];
objfilestream.Read(mybytearray, 0, len);
var myservice = new WebService();
var fileurl = myservice.SaveDocument(mybytearray, FileUpload1.FileName);
Image1.ImageUrl = fileurl;
}
File.Delete(savePath);
}
}
}
}
WebService.asmx.cs:
namespace TestAspNetWebApp
{
using System.IO;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService : System.Web.Services.WebService
{
private const string uploadDir = "uploads-websevice";
[WebMethod]
public string SaveDocument(byte[] docbinaryarray, string docname)
{
string strdocPath;
string docDirPath = Server.MapPath("\\") + uploadDir + "\\";
strdocPath = docDirPath + docname;
if (!Directory.Exists(docDirPath))
Directory.CreateDirectory(docDirPath);
var objfilestream = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
objfilestream.Close();
return "http://localhost:57064/" + uploadDir + "/" + docname;
}
}
}
Please add some example of your code to help you to define the problem and to solive it.
It seems that server returns all headers and also 'Content-type' as usual.
using (var client = new WebClient())
{
string uri = "http://chronicletwilio.azurewebsites.net/res/12345.png";
byte[] data = client.DownloadData(uri);
string contentType = client.ResponseHeaders["content-type"];
// contentType is 'image/png'
}
I figured out the problem. Even though the content type header was set, the file was not being read as an image, but only as a file. That being the case the 3rd party API I was using was not correctly reading it and complained about the content type. The fix ended up being chaning my method to the following:
[WebMethod]
public string SaveImage(byte[] docbinaryarray, string docname)
{
string strdocPath;
string docDirPath = Server.MapPath("/") + uploadDir;
strdocPath = docDirPath + docname;
if (!Directory.Exists(docDirPath))
Directory.CreateDirectory(docDirPath);
using (Image image = Image.FromStream(new MemoryStream(docbinaryarray)))
{
image.Save(strdocPath, ImageFormat.Png); // Or Png
}
return "http://example.com/" + uploadDir + docname;
}

How to get HTML for ASP.NET webrequest

I want to get the source code of this page.
string adres = "https://betorder.com/Sports.html";
WebRequest gelenIstek = HttpWebRequest.Create(adres);
WebResponse gelenCevap;
using (gelenCevap = gelenIstek.GetResponse())
{
using (StreamReader donenDeger = new StreamReader(gelenCevap.GetResponseStream()))
{
string gelenBilgi = donenDeger.ReadToEnd();
string gonder = gelenBilgi;
div.InnerHtml = gonder;
}
}
Use http schema to make a request and add the html to some div, like below:
ASPX page
<form id="form1" runat="server">
<asp:Panel runat="server" ID="pnlHtml"></asp:Panel>
</form>
Your code-behind:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var adres = "http://betorder.com/Sports.html";
var gelenIstek = HttpWebRequest.Create(adres);
WebResponse gelenCevap;
using (gelenCevap = gelenIstek.GetResponse())
{
using (var donenDeger = new StreamReader(gelenCevap.GetResponseStream()))
{
var response = donenDeger.ReadToEnd();
var divcontrol = new HtmlGenericControl
{
TagName = "div",
InnerHtml = response
};
pnlHtml.Controls.Add(divcontrol);
}
}
}

Downloading large files asp.net mvc 3?

I have a large pdf file (upto 2 GBs) on a database server which I want to send to client for download. Also, I have size limitations on my web server and cannot store complete file on it, after requesting from data server. I am using asp.net mvc 3. Any suggestions on how can I accomplish this? Also I want it to be asynchronous since I don't want to block the user from clicking other buttons on the web page.
I have tried using this code.
//code for getting data from data server into inputstream
HttpContext.Response.ContentType = "application/pdf";
HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Response.BufferOutput = false;
try
{
using (Stream inputStream = resp.GetResponseStream())
{
byte[] buffer = new byte[SegmentSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, SegmentSize)) > 0)
{
HttpContext.Response.OutputStream.Write(buffer, 0, bytesRead);
HttpContext.Response.Flush();
}
}
}
catch (Exception ex)
{
//some code
}
This downloads the file but then I don't know how to make it asynchronous? Also is there any other way to do the download that would be asynchronous too?
You can use AJAX which is Asynchronous. For that use a library like JqueryUI and a plugin, take a look a this example
http://www.plupload.com/example_custom.php
Im sure this will do! :D
Turns out in my final application I did not use web service but simple AJAX and ASPX pages this is how I got it done!
Default.ASPX file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CloudWF._Default"
Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link type="text/css" href="css/redmond/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="jsEng" runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.7.2.min.js" />
<asp:ScriptReference Path="~/js/jquery-ui-1.8.21.custom.min.js" />
</Scripts>
</asp:ScriptManager>
<input type='submit' value='Process New Records' id='trigger' onclick='BeginProcess(); return false;' />
</div>
</form>
</body>
<script type="text/javascript">
var btnStart;
$(function () {
btnStart = $("#trigger").button();
imgLoad = $("#loader").hide();
});
function BeginProcess() {
btnStart.val("Collecting Data...");
//to get the value of the radiobuttons
//alert($('input[name=A]:checked').val()) --> [name=*] where *= whatever the name of the radioset
// Create an iframe.
var iframe = document.createElement("iframe");
// Point the iframe to the location of
// the long running process.
iframe.src = "process.aspx";
// Make the iframe invisible.
iframe.style.display = "none";
// Add the iframe to the DOM. The process
// will begin execution at this point.
document.body.appendChild(iframe);
btnStart.val("Processing...");
imgLoad.show();
btnStart.button("disable");
}
function UpdateProgress(RecordComplete, Message, step) {
btnStart.val("Downloaded Record " + RecordComplete + Message);
$("#progressbar").progressbar({
value: step
});
if (step >= 100) {
imgLoad.hide();
btnStart.val("Download Complete!");
}
}
</script>
Process.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
public partial class process : System.Web.UI.Page
{
WebClient wc = new WebClient();
Dictionary<string, string> AudioURLs = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
// Padding to circumvent IE's buffer*
Response.Write(new string('*', 256));
Response.Flush();
ProcessRecords();
}
public void ProcessRecords()
{
int recTotal;
recordList = (IQueryable<Record>)(Session["UNPROCESSED"]);
recTotal = recordList.Count();
if (recordList.Count() > 0)
{
foreach (Record record in recordList)
{
try
{
curRow++;
step = ((decimal)curRow / (decimal)recTotal) * 100;
CreateDictionary();
CreateFolderwithAudios(record.tSessionID);
//record.processed = true;
db.SubmitChanges();
UpdateProgress(curRow, " of " + recTotal, step);
}
catch (Exception x)
{
HttpContext.Current.Response.Write("Exception: " + x.Message);
}
}
Session["UNPROCESSED"] = null;
}
}
public Dictionary<string, string> CreateDictionary()
{
AudioURLs.Clear();
#region Add Values to Dictionary
return AudioURLs;
}
public void DownloadAudios(string _subFolder, Dictionary<string, string> _AudioSources)
{
foreach (KeyValuePair<string, string> kvp in _AudioSources)
{
if (kvp.Value.StartsWith("http://"))
{
try
{
wc.DownloadFile(kvp.Value, audiosPath + "\\" + _subFolder + "\\" + kvp.Key + ".wav");
}
catch (WebException webex)
{
throw new WebException(webex.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
public void CreateFolderwithAudios(string folderName)
{
try
{
//create the folder where the audios are going to be saved
Directory.CreateDirectory(audiosPath + folderName);
//create and read the Dictionary that contains the URLs for the audio files
DownloadAudios(folderName, AudioURLs);
}
catch (AccessViolationException ae)
{
HttpContext.Current.Response.Write(ae.Message);
}
catch (System.Exception x)
{
HttpContext.Current.Response.Write(x.Message);
}
}
protected void UpdateProgress(int PercentComplete, string Message, decimal step)
{
// Write out the parent script callback.
Response.Write(String.Format(
"<script>parent.UpdateProgress({0}, '{1}',{2});</script>",
PercentComplete, Message, step));
// To be sure the response isn't buffered on the server.
Response.Flush();
}

problem getting dynamic xml

i have an ASP.net page that generates dynamic xml but the get statement of a jquery ajax request won't recognize the file. this solution worked with a php doc getting the dynamic xml. The asp.net page that generates xml works fine. The ajax request never succeeds. any ideas as to why much appreciated
<%# Page Language="C#" AutoEventWireup="true" Debug="true" ContentType="text/xml" %>
<%# Import Namespace="System.Xml" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Data" %>
<script runat="server">
protected void Page_Load(object source, EventArgs e)
{
XmlDocument doc = new XmlDocument();
// XML declaration
XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
doc.AppendChild(declaration);
// Root element: article
XmlElement root = doc.CreateElement("statements");
doc.AppendChild(root);
string connStr = "";
string sqlStr = "SELECT [title], [statement] FROM [a table]";
using (SqlConnection connection = new SqlConnection(connStr))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = sqlStr;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
int indexOftitle = dataReader.GetOrdinal("title");
int indexOfstatement = dataReader.GetOrdinal("statement");
while (dataReader.Read())
{
string title = (string)dataReader.GetValue(indexOftitle);
string statement = (string)dataReader.GetValue(indexOfstatement);
XmlElement xstatement = doc.CreateElement("statement");
root.AppendChild(xstatement);
XmlAttribute xtitle = doc.CreateAttribute("title");
xtitle.Value = title;
xstatement.Attributes.Append(xtitle);
XmlAttribute xtext = doc.CreateAttribute("text");
xtext.Value = statement;
xstatement.Attributes.Append(xtext);
}
}
connection.Close();
}
}
doc.Save(Response.OutputStream);
}
</script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "../data/genxml_docstate.aspx",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml) {
alert("ok");
var items = [];
var header = 'some initial html'
$(xml).find("statement").each(function () {
var title = $(this).attr("title");
var titleid = (title.substr(0, 8)).replace(" ", "_");
items.push('<li id="' + titleid + '">' + title + '</li>');
});
$('#doclist').append(items.join(''));
$("#doc_box_right").html(header);
$(xml).find("statement").each(function () {
var title = $(this).attr("title");
var titleid = (title.substr(0, 8)).replace(" ", "_");
var id = '#' + titleid;
var statement = $(this).attr("text");
$(id).css("cursor", "pointer");
$(id).mouseover(function () {
$(id).css("background-color", "gray");
$("#doc_box_right").html('<h2>' + title + '</h2><p>' + statement + '</p>');
});
$(id).mouseleave(function () {
$(id).css("background-color", "transparent");
$("#doc_box_right").html(header);
});
});
}
</script>
#Chris , can you try firebug .net panel and see if you are getting results for the ajax...so that we can eliminate the issue.It shows the errors also if there are any.
You are not setting the mime type of the response to text/xml, so the browser will not recognize it as XML.
Make sure you add a:
Response.ContentType("text/xml");
before you save to the output stream.

Resources