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 !
Related
i want to display these json data into a html table. i am trying to do many things but i cant figure out how can i do it. So anyone can please help me to fix it.
the json data set will appear in the console. but i cant set it to a table.
this is my model
public function displayRecords()
{
$this->db->select('A.*');
$this->db->from('rahu AS A');
$this->db->where('A.status',1);
return $this->db->get()->result_array();
}
this is my controller
public function allrecodes()
{
/*script allow*/
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed here.');
}
$response= array();
$response['result'] = $this->RahuModel->displayRecords();
echo json_encode($response);
}
this is my js
var get_rec = function(){
//alert("WWW");
$.ajax({
//request ajax
url : "../dashbord/allrecodes",
type : "post",
contentType: "application/json",
dataType : "json",
success: function(dataset) {
//var myobject = JSON.stringify(result);
//alert(myobject[0]);
console.log(dataset);
console.log(dataset.result[0]['id']);
},
error: function() { alert("Invalide!"); }
});
};
the json dataset will appear in console.
And also this get_rec() in js file will called top of the page.
$(document).ready(function() {
//alert("Hello, world!");
get_rec();});
can anyone please help me to fix it.. thank you !!
There is no "simple" way to do it. You will have to loop through the resultset and render the html.
function renderTable(data) {
var result = ['<table>'];
var header = false;
for (var index in data) {
var row = data[index];
if (!header) {
// Create header row.
header = Object.keys(row);
var res = ['<tr>'];
for (var r in header) {
res.push("<th>" + header[r] + "</th>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
// Add data row.
var res = ['<tr>'];
for (var r in header) {
res.push("<td>" + row[header[r]] + "</td>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
result.push('</table>');
return result.join("\n");
}
document.getElementById('output').innerHTML = renderTable(data);
Have a div tag with id output on your HTML
<div id="output"></div>
I have a datatable in C# and I am converting it to html table like below.
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder html = new StringBuilder();
html.Append("<table id='example' class='table table-striped table-bordered' cellspacing ='0' width ='100%' font size='8' aria-hidden='true'>");
//add header row
html.Append("<thead>");
html.Append("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<td>" + dt.Columns[i].ColumnName + "</td>");
html.Append("<td>" + "Action" + "</td>");
html.Append("</tr>");
html.Append("</thead>");
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("<td><input type=\"button\" value=\"Delete\" onclick=\"deleteRow(this)\"/></td>");
html.Append("</tr>");
}
html.Append("</table>");
return html.ToString();
}
This is showing a table in my aspx page like below:
Name City Quantity Action
A X 5 Delete
B Y 10 Delete
C Z 15 Delete
When I click "Delete" button for a row, the function below works and the row is gone from the result table.
<script>
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
What I want is that, in addition to the current process, I need to run a SQL query to update IsRemoved flag for this data in my SQL Server 2014 table.
The query I need to run: Update MyTable set IsRemoved=1 where Name='A' and City='X'
I could not manage to run it in JavaScript function, and could not find a way to execute another function in C# after the JS function. OnClientClick is not working since it is not an asp:Button, and when I try to use asp:Button instead of input element, it does not show it on the screen.
How can I change data in DB here for such an example? Please note that I am trying not to use a GridView. Any help would be appreciated.
EDIT: By using Ajax, how can I send paramaters from my ajax call to c#:
I am trying:
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
data: JSON.stringify({ name: **<nameshouldcomehere>**, city:**<cityshouldcomehere>** }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
I can't find how to set name and city dynamically based on the row clicked the delete button, any tips?
In your .cs page create a WebMethod which will mark the Database entry as IsRemoved=1 as:
[System.Web.Services.WebMethod]
public static string DeleteRowFromDB(string name,string city)
{
var status = "0";
//Your code to mark `IsRemoved=1` for the selected entry goes here and set the `status` variable as status="1" if the DB command successed.
return status;
}
And then create a function with an ajax call to invoke the created WebMethod and remove the row from HTML if the status is true as:
function deleteRow(btn)
{
var row = btn.parentNode.parentNode;
var cells = row.getElementsByTagName("td");
var reqData = JSON.stringify({ name: cells[0].innerText, city:city=cells[1].innerText });
//now make a call to the `WebMethod` via `ajax`.
$.ajax({
type: 'POST',
url: 'mypage.aspx/DeleteRowFromDB',
contenttype: 'application/json; charset=utf-8',
data: reqData,
datatype: 'json',
success: function (response) {
if(response === "1") {
row.parentNode.removeChild(row);
}
else
{
//do other stuff
}
},
error: function (error) {
//handle the error
}
});
}
Note: if the response variable in the ajax success function doesn't have the desired value try to look for its response.d property value.
I'm trying to bind and display 4 concatenate item in dropdownlist using ajax.
Like this eg. (127,CoilWt,1,KGS ) one of the value in dropdownlist should appear like this.from database.
In database i am selecting
`select CODE_VALUE,CODE_DESC,CODE_SUB_VALUE,CODE_SUB_DESC FROM TCODE
html part
<td><select class='form-control' id='Certific'><option value='' disabled='disabled' selected='selected'>Please select a name</option></select></td>
script part
$(function () {
$.ajax({
type: "POST",
url: "TDC.aspx/GetCertificate",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var Certific = $("[id*=Certific]");
Certific.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
Certific.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
c# side
public class GetCertificate
{
public int ID { get; set; }
public string Code_Desc { get; set; }
}
[WebMethod]
public static List<GetCertificate> GetCertificate()
{
string connStr = ConfigurationManager.ConnectionStrings["conndbprodnew"].ToString();
OracleConnection objconn = new OracleConnection(connStr);
string prop_name, tdc_property = "", qry = "";
qry = "SELECT CODE_DESC from tdc_product1 ";
OracleCommand objFetchCmd = new OracleCommand(qry, objconn);
List<GetCertificate> Certificate = new List<GetCertificate>();
objconn.Open();
OracleDataReader ReadData = objFetchCmd.ExecuteReader();
while (ReadData.Read())
{
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
}
return Certificate;
}
Where is the mistake i am trying like this but getting error at GetCertificate.ID .Any idea would be appreciated.
I guess you're making mistake at:
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
GetCertificate seems to be a type not a instance of object.
You should try something like:
Certificate.Add(new GetCertificate { ID = ReadData["ID"].ToString(), CODE_DESC = ReadData["CODE_DESC"].ToString() } );
Please be aware that I wrote this without any IDE, so there could be typo/syntax error, but you get the idea.
Small hint: Of course there're plenty of room for code refactor in your code (e.g. rename Certificate to Certificates), but that is another topic.
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")
I've ran into this strange JSON behavior.. I just cant figure out what the hell is going on..
I've got a WebMethod in my asp.net page.. It repetitively calls as page loads through jQuery AJAX.. Everything goes pretty smooth but what strange thing happens is that the data I sens to my jQuery ajax is not the SAME I just sent.. :S
here is not code of page method
[WebMethod()]
public static List<Unister.UnisterCore.Core.Domain.Comment> LoadComments(long objID, int sysID)
{
if (objID == 0)
return null;
UnisterWeb.UserControls.Presenter.CommentsPresenter _presneter;
_presneter = new UnisterWeb.UserControls.Presenter.CommentsPresenter();
List<Unister.UnisterCore.Core.Domain.Comment> comments = new List<Unister.UnisterCore.Core.Domain.Comment>();
comments = _presneter.LoadComments(sysID, objID);
if (comments.Count == 0)
return null;
return comments;
}
Here returning list is what I got from my presenter layer but when I receive that in my js method, its either null or previous value.
Here is my jQuery method..
function LoadComments(SysID, ObjID) {
if (parseInt(SysID) == 0 || parseInt(ObjID) == 0)
return;
var args = 'objID:' + ObjID + ',sysID:' + SysID;
$.ajax({
type: "POST",
url: "/dashboard/default.aspx/LoadComments",
cache: false,
data: '{' + args + '}',
contentType: "application/json",
dataType: "json",
success: function(result) {
if (result.d != null) {
comments = new Array();
$.each(result.d, function(key, val) {
data = new Object();
data.CommentID = val.CommentID;
data.Body = val.Body;
codate = new Date(parseInt(val.CreateDate.replace("/Date(", "").replace(")/", ""), 10));
var fdate = dateFormat(codate, "isoUtcDateTime");
ldate = $.timeago(fdate);
data.CreateDate = ldate;
data.CommentByAccountID = val.CommentByAccountID;
comments.push(data);
});
var boxid = "#commentBox_" + ObjID;
$(boxid).setTemplateURL("../Templates/comments.htm");
$(boxid).processTemplate(comments);
}
}
});
}
Please help me..
I found the solution... :)
First thing we could do is make our request async: false (BUT it'll impact our performance).. Instead, Im sending an ID (in my case SysID) and also bind it with my DIV id like the code below..
<div id ="comment_<%= SysID %>"></div>
In my jQuery function I use
var ID = "#comment_" + val.SysteID;
$(ID).setTemplateURL("../Templates/comments.htm");
$(ID).processTemplate(comments);
Hope it helps you guys too ... :)