problem getting dynamic xml - asp.net

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.

Related

How can I know the type of change happened to the database using SQL Dependency

I have the following code which displays live data using SignalR. The table gets updated instantly using SignalR once a row is inserted, updated, or deleted. However, I would like to know in particular the type of change that happened to the database (whether it's an update, delete, or insert). I understand that the onchange() method detects changes on the database, but how can I determine what type of change it is?
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionCustomer"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[CustomerName] FROM [CustomerInfoes] ", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
Id = (int)x["Id"],
CustomerName = (string)x["CustomerName"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CustomerHub.Show();
}
Hub:
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CustomerHub>();
context.Clients.All.displayCustomer();
}
View
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var cus = $.connection.customerHub;
// Declare a function on the job hub so the server can invoke it
cus.client.displayCustomer = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblInfo');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
'<tr>' +
'<td>' + model.Id + '</td>' +
'<td>' + model.CustomerName + '</td>' +
'<tr>'
);
});
}
});
}</script>
You can easily find out the change type by looking at eventArgs.Info property.

Google chart is not loading in asp.net using JSON

I am trying to visualize data using google charts.But the chart is not displaying.I want to display data which is retrieved from sqlserver database
here is my code.
<div id="chart_div" style="width:500px;height:400px">
<%-- Here Chart Will Load --%>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var jdata = $.ajax({
url: "GetData.aspx",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jData);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: {
title: 'Chess opening moves',
subtitle: 'popularity by percentage'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'amount' } // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
};
</script>
</div>
GetData.aspx
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string arr = JsonConvert.SerializeObject(get(), Formatting.None,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Response.Write(arr);
}
private object get()
{
List<object> ls = new List<object>();
SqlConnection con = new SqlConnection("Data Source=dell-pc;Initial Catalog=hospital;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select top(5) p_id, amount from payments", con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ls.Add(dr);
}
return ls;
}
}
The JsonArray loads as follows.
[{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT1",7000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT2",35000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT8",95000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT10",51000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT3",1200.0000],"HasErrors":false}]
I think there is something wrong when json is loading. please help
The main reason here that you fail to load json data is probably because you use a full aspx page GetData.aspx (and there you send wrong header, content type)
Change that to a handler, make a new handler not just rename the page, something like getdata.ashx and place there your code.
Be sure to send the correct content type context.Response.ContentType, and check that you send only the correct json data
the answers here can help : ASP.NET Returning JSON with ASHX

ASP.NET: Relative Path with Root Operator('~') in Client side

I have implemented a web page with asp.net.
It has some ajax function.
in ajax function, Get a image path from server side webMethod.
The image path consist of root operator, for example "~/Images/Icons/SendEmail.png".
In Client side, I want to set image path to img element.
How can I set the image from this relative path?
Here is my code snippet.
Please refer this and give me some advices. Thank you in advance.
Clien side
function DrawImage() {
$.ajax({
type: 'POST',
url: '../Management/GetImage',
data: '{Index: "' + Index + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (resp) {
if (resp.d == null) {
return;
}
var ImagePath = resp.d;
var image = document.createElement('img');
image.src = ImagePath; // e.g. "~/Images/Image.png"
$(imageDiv).append(image);
},
error: function (msg) {
alert("Failed to Image: " + msg.statustext);
}
});
}
Server Side WebMethod
[WebMethod]
public static string GetImage(string Index)
{
string conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Select_ImagePath";
command.Parameters.AddWithValue("#Index", Index);
string imgPath = "";
try
{
conn.Open();
SqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
imgPath = (string)dataReader["Image_Path"]; // e.g. "~/Images/Image.png"
}
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
return imgPath;
}
I solved this problem by just implementing some function in javascript like below.
function ConvertRelPathToAbsPath(path)
{
var absPath ="";
if (path.length > 0)
absPath = window.location.protocol + '//' + location.host + path.substr(1);
return absPath;
}

Binding Lable from webmethod using ajax

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

responseXML from XMLHttpRequest Object doesn't work

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);
}
}

Resources