I am using asp.net application and using ajax call,below is my code.Below is my web method which is working fine and give response of ajax call.
ADController adc = new ADController();
DataTable dt = adc.GetGeneral(Convert.ToInt32( AnnouncementId));// GetAnnouncementsByIDAndRead(Convert.ToInt32(AnnouncementId), Convert.ToInt32(userid));
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in dt.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
if (col.ColumnName == "description")
{
childRow.Add(col.ColumnName, HttpUtility.HtmlDecode( Convert.ToString( row[col]) )as object);
}
else
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
following is my ajax code ,which is working fine and giving data on call fine.
function fnshowAncDetails(AnnouncementId, userid) {
$(".loading").show();
var url = $("[id$='hdURLt']").val();
$("[id$='btnSaveMD']").show();
$.ajax({
type: "POST",
url: url + "/GetInfo.aspx/General",
data: '{AnnouncementId:"' + AnnouncementId + '",userid:"' + userid + '"}',
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: OnSuccessSetCGiven,
error: function (response) {
}
});
var vtext = $("[id$='lblAnnoucement']").text();
if (vtext != 0) {
vtext = vtext - 1;
}
$("[id$='lblAnnoucement']").text(vtext);
}
below is my success method
function OnSuccessSetCGiven(response) {
var parsed = $.parseJSON(response.d);
$("[id$='htititlen']").text(parsed[0].Title);
$("[id$='divNotifBody']").text(parsed[0].Description);
$("[id$='divadded']").text("By:"+parsed[0].FirstName + " " + parsed[0].LastName);
$("#divNotifdetails").modal('show');
$(".modal-backdrop").css('z-index', '0');
$(".loading").hide();
var formattedTime = parsed[0].stime.Hours + ":" + parsed[0].stime.Minutes;
//$("[id$='divtime']").text(formattedTime);
$("[id$='divdate']").text("Time:" +parsed[0].startdate + " " + formattedTime);
}
Now my question is in The Description there may be html tags, means formatted htmls,like <p>xxx</p><b>sdf</b>. So it not loaded as bold,
how can I render formatted html?
Use jQuery .html function and not .text:
function OnSuccessSetCGiven(response) {
...
$("[id$='divNotifBody']").html(parsed[0].Description);
...
}
But note that you will have JS injection vulnerability, so you must clean the HTML code in the description field and remove unwanted attributes & tags (for example: <script>, <any onclick=""> etc.)
Update:
By the way, I am not familiar with this selection syntax:
$("[id$='divNotifBody']")
Assuming that you want to select a div with the id "divNotifBody", Why not just use:
$("#divNotifBody")
Related
I need to pass label value to static 'web method' in where clause using ajax. I am creating a structured chart where, i need to show only data and sub data of users who have currently logged in.
i am not getting any idea of how to pass asp controls value to static method.i have even tried to pass label value from jquery and ajax but, i am getting undefined error.please help to solve this error
My code is
[WebMethod]
public static List<object> GetChartData(string name)
{
string query = "SELECT * ";
query += " from abc where ID=#ID";
string constr = ConfigurationManager.ConnectionStrings["constr1"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("#ID",name);
----i am getting error on lblsubid----
List<object> chartData = new List<object>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["ID"], sdr["Name"], sdr["Emailid"] ,sdr["SubId"]
});
}
}
con.Close();
return chartData;
}
}
}
frontend code :-
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var url = window.location.pathname;
var action = url.substr(url.lastIndexOf('/') + 1);
document.getElementById("lblsubid").innerHTML = action;
$.ajax({
type: "POST",
url: "Test.aspx/"+action+"GetChartData",
data: '{name: "' + action + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < r.d.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: employeeName + '<div>(<span>' + designation + '</span>)</div>'
}, reportingManager, designation]]);
}
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart">
</div>
<asp:Label runat="server" ID="lblsubid"></asp:Label>
In your ajax call to your WebMethod you are not passing in anything
You need to pass in your label text
data: '{}', -- your label value here
And in your method: (add parameters)
[WebMethod]
public static List<object> GetChartData(string LabelText)
And when building your query:
cmd.Parameters.AddWithValue("#ID",LabelText);
I coded up just like everybody else on the net but my WebMethod isn't getting hit from the post action. I believe my code is fine but I'll post my code just in case.
I put a breakpoint in the WebMethod, this is how I know it isn't being called.
Any help would be appreciated.
AXAJ
var div = document.getElementById(this.id);
var divid = div.getElementsByClassName("portlet-id");
varSQL="UPDATE [ToDoTrack] SET [Status] = '" + this.id + "' WHERE [ID] = '" + divid[0].innerHTML + "'";
var item = {};
item.status = this.id;
item.id = divid[0].innerHTML;
var Data = '{varSQL: ' + varSQL + ' }'
$.ajax({
type: "POST",
url: "ToDoTrack.aspx/UpdateDB",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
window.location.reload();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
Code Behind
[WebMethod]
[ScriptMethod]
public static void UpdateDB(string varSQL)
{
string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(varSQL))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a problem the data object, it's a string not an object
Its not recommended to create the SQL on client side, it's a security flaw unless it's an application
//Problem is a string not object
var Data = '{varSQL: ' + varSQL + ' }'
//Solution below
var Data = {'varSQL': varSQL };
// Or this
var Data = 'varSQL='+varSQL;
The code seemed to work fine but if you have this issue in the future, these are the things I got from the internet that you seem to need for ajax post to work with WebMethods:
Ensure your URL in AJAX is correct
Ensure your json is well formed
Set <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">, my script manager was in my site.master
Set settings.AutoRedirectMode = RedirectMode.Off; in the App_Start>RouteConfig.cs file
I have one WebMethod that will execute some DB search and return it's data in some HTML template. I need to execute this method using jquery to populate an area of the website but the problem is that my website URL/URI is dynamic.
My URL is http://site/school-name/home. The school-name will always change to indicate wich school i'm accessing.
I have accomplished so far:
$.ajax({
type: "POST",
url: "/Default.aspx/BuscaEquipe",
data: { 'pIndex': pIndex, 'pLimite': 4, 'pUnidadeCE': codigoEmitente },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
failure: function(response) {
alert(response.d);
}
});
and the WebMethod:
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
var objEquipe = new Equipe { EquipeUnidadeCE = pUnidadeCE, EquipeAtivo = 1 };
var CaminhoImagem = Configuracoes.CaminhoVirtual + "Controles/Redimensiona.ashx?img=" + Configuracoes.CaminhoVirtual + "images/equipe/" + pUnidadeCE + "/";
if (!objEquipe.Listar(objEquipe)) return "";
var depoimentos = objEquipe.lstEquipe.Skip(pIndex).Take(pLimite);
var objJson = new JavaScriptSerializer().Serialize(depoimentos.Aggregate("", (current, equipe) =>
current + ("<div class='col-lg-3 col-md-3 col-sm-3'><img src='" + CaminhoImagem + equipe.EquipeImagem + "&w=400&h=400' alt='" + equipe.EquipeNome + "' class='img-circle img_perfil'><div class='nome_perfil text-center'>" + equipe.EquipeNome + "</div></div>")));
return objJson;
}
Using like this i get a 401 Not Authorized and if i try to use my full URL http://site/school-name/Default.aspx/BuscaEquipe i get a 404.
P.S. I have already used this same method in another project and it worked fine but i can't figure out what's wrong in this one, i think it might be related to the URl but i'm not sure.
the problem is with your URL
Use the ResolveClientUrl() method
<%= ResolveUrl("~/Default.aspx/BuscaEquipe") %>
And you must Have [WebMethod] attribute before your static server function
[WebMethod]
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
//Code
}
Your data:
var requestData= JSON.stringify({
pIndex: pIndex,
pLimite: 4,
pUnidadeCE: codigoEmitente
})
and then
data:requestData
I' m trying to create a search box with autocomplete property and using a handler.
I got all words from database but can not show them.
It' s jquery part:
$(function () {
$("#search-box").autocomplete({
source: "KeywordHandler.ashx",
minLength: 1,
#*select: function (event, ui) {
alert(ui.item.id + " / " + ui.item.value);
}*#
});
});
It' s handler part:
public class KeywordHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Keyword from [dbo].[Log] where " + "Keyword like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["Keyword"])
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
At handler, I can get all the words which I need but can not show them as offered keywords at search box.
Is there any idea?
You may use something like below. Pay attention to "refresh" part. You should return your query result as JSON from webservice and then parse it. After parse, you can create list item for every search result item as I indicated in JQuery code (the last part of the code).
*I wrote my answer as supposing you are getting the result from your service properly.
HTML
<div id="assignDiv" style="display:none;">
<div data-demo-html="true" data-demo-js="true" data-demo-css="true">
<h3>Select contact:</h3>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Search contact..." data-filter-theme="d"></ul>
</div>
<input type="button" value="Send to selected contact" id="assignToBtn" />
</div>
JQuery
$("#autocomplete").on("listviewbeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length > 2) {
$ul.html("<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>");
$ul.listview("refresh");
$.ajax({
type: "POST",
crossDomain: true,
url: serverAddress + "General.asmx/AutoComplete",
data: "{'q': '" + $input.val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.then(function (response) {
var JsonObj = jQuery.parseJSON(response.d);
$.each(JsonObj, function (i, val) {
html += "<li><a href='javascript:changeAutoCompleteText(\"" + val + "\");'>" + val + " <i style='color:grey;font-weight:lighter;'>(</i><i style='text-decoration:underline;color:grey;font-weight:lighter;'>" + val + "</i><i style='color:grey;font-weight:lighter;'>)</i></a></li>";
});
$ul.html(html);
$ul.listview("refresh");
$ul.trigger("updatelayout");
});
}
});
I wrote a method (with WebMethod attribute) which give me list of books :
public struct BOOK
{
public string BOOK_NAME;
public string BOOK_DESC;
}
[WebMethod]
public static List<BOOK> GetMyBooks()
{
string _connString = "Data Source=.;Initial Catalog=BookStore;Integrated Security=True";
SqlConnection _conn = new SqlConnection(_connString);
_conn.Open();
SqlCommand _com = new SqlCommand("select * from Book_TBL where IsActive='True' ", _conn);
_com.CommandType = System.Data.CommandType.Text;
SqlDataAdapter bookdataAdapter = new SqlDataAdapter(_com);
DataSet bookDS = new DataSet();
bookdataAdapter.Fill(bookDS, "Book_TBL");
List<BOOK> bookList = new List<BOOK>();
BOOK book;
foreach (DataRow dr in bookDS.Tables["Book_TBL"].Rows)
{
book = new BOOK();
book.BOOK_NAME = dr["book_name"].ToString();
book.BOOK_DESC = dr["book_desc"].ToString();
bookList.Add(book);
}
return bookList;
}
and i wrote a script that call the "GetMyBooks" method every 5 second and show it in a div tag by id:"pejiGrid" in my WebForm2.aspx :
<script>
$(document).ready(function () {
$("#go").click(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetMyBooks",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (var i = 0; i < response.d.length; i++) {
$("#pejiGrid").append("<tr><td>" + response.d[i].BOOK_NAME + "</td><td>" + response.d[i].BOOK_DESC + "</td></tr>");
}
}, });
}, 5000);
});
});
but my method and script append duplicate information in my "#pejiGrid", i want to show this information only once, is there any way,which i can do it by script? if it is not possible, what is the solution?
Everything in code is OK. You need just a small correction in your script. Replace the success function body with this code:
var htm = [];
for (var i = 0; i < response.d.length; i++) {
htm.push("" + response.d[i].BOOK_NAME + "" + response.d[i].BOOK_DESC + "");
}
$("#pejiGrid").html(htm.join(''));
If I correctly understood the question the problem was in using the 'append' method of jQuery, which was appending all new data received from server. Instead of that you were needed to replace old data with new one. So you need to use the 'html' method to replace the content of div.
One more advice. It will be better to store methods like 'GetMyBooks()' in web services files, developed specially for that purpose.
Wish you all the best !