How to append div by ajax - javascript

i'm trying to retrieve values from database after that how can i pass those values from that static method and append to div in ajax ,Here is the C# code for that
[WebMethod]
[ScriptMethod]
public static string[] Cdetails(Cmpny cmpny)
{
StringBuilder html = new StringBuilder();
string strCname = cmpny.Cname;
string strCvalue= cmpny.Cvalue;
string strLvl = cmpny.Clevel;
int intLvl = Convert.ToInt32(strLvl);
List<string> company = new List<string>();
if (intLvl == 1)
{
SqlConnection conn = new SqlConnection(HttpContext.Current.Session["ConnectionString"].ToString());
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Clientid,C_Name,C_website,Status,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy from clientDetails where Clientid=#Clientid and C_Name=#C_Name";
cmd.Parameters.AddWithValue("#C_Name", strCname);
cmd.Parameters.AddWithValue("#Clientid", strCvalue);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
company.Add(string.Format("{0}-{7}", sdr["Clientid"], sdr["C_Name"], sdr["C_website"], sdr["Status"], sdr["CreatedDate"], sdr["CreatedBy"], sdr["ModifiedDate"], sdr["ModifiedBy"]));
}
}
conn.Close();
}
}
//else
//{
// return strLvl.ToArray();
//}
return company.ToArray();
}
and ajax method is here
<script type="text/javascript">
function OnTreeClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var nodeClick = src.tagName.toLowerCase() == "a";
if (nodeClick) {
var nodeText = src.innerText || src.innerHTML;
var nodeValue = GetNodeValue(src);
var nodePath = src.href.substring(src.href.indexOf(",") + 2, src.href.length - 2);
//alert(nodePath.toLowerCase());
if (nodePath.indexOf("\\") > -1)
{
var level = "2";
// alert("Second level ");
}
else
{
var level = "1";
// alert(" first level ");
}
//var nodestat =
alert("Text: " + nodeText + "," + "Value: " + nodeValue );
var cmpny = {};
cmpny.Cname = nodeText;
cmpny.Cvalue = nodeValue;
cmpny.Clevel = level;
$.ajax({
type: "POST",
url: "CS.aspx/Cdetails",
data: '{cmpny: ' + JSON.stringify(cmpny) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
div_ClientLoc.innerHTML = response.d;//here how can i append those tag and div_ClientLoc is div id
// window.location.reload();
}
});
return false;
}
return true;
}
function GetNodeValue(node) {
var nodeValue = "";
//alert(node.href.toLowerCase());
var nodePath = node.href.substring(node.href.indexOf(",") + 2, node.href.length - 2);
// alert(nodePath.toLowerCase());
var nodeValues = nodePath.split("\\");
if (nodeValues.length > 1)
nodeValue = nodeValues[nodeValues.length - 1];
else
nodeValue = nodeValues[0].substr(1);
return nodeValue;
}
can anyone please explain me how can i solve this problem

You are overwriting the html of div_ClientLoc by assigning the result to innerHTML. You can use jQuery append() method to append the response result in existing html of div_ClientLoc.
$("#div_ClientLoc").append(response.d);
Or you can also append the result in div_ClientLoc.innerHTML by using Addition Assignment Operator += instead of assignment operator = like as under
div_ClientLoc.innerHTML += response.d;

You need to get a hold of the element that you are appending to, then insert the HTML.
You can use document.getElementById('div_ClientLoc') to get your target element.
insertAdjacentHTML will insert the content at beforeend, which is before the closing tag.
document.getElementById('div_ClientLoc').insertAdjacentHTML('beforeend', response.d);

Related

How to read the content from a C# HttpResponseMessage in javascript?

I have a string called csv that is literally just that, things like "name,lastname,age,height,etc"
Then I send it to the backend like this..
var csv = exportRequests.GetCSV();
var filename = string.Format("{0}-{1}-{2:yyyy-MM-dd_hh-mm-ss-tt}.csv", "Request", requestStatus.ToUpperInvariant(), DateTime.Now);
var stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(csv);
writer.Flush();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("text/csv");
//var test = new FileDetailViewModel();
//test.Name = filename;
//test.Rows = csv;
return Ok(result);
I then read it on the backend, but where is the actual content?? Surely the bytes should be somewhere. The content property only has the headers.. This is taking place on an old system using $.ajax to make the call.
Thanks
I do not think it is possible to read content via HttpResponseMessage in JavaScript. You can only download content.
public HttpResponseMessage GetCsv()
{
var csv = exportRequests.GetCSV();
var filename = string.Format("{0}-{1}-{2:yyyy-MM-dd_hh-mm-ss-tt}.csv", "Request", requestStatus.ToUpperInvariant(), DateTime.Now);
var stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(csv);
writer.Flush();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
return result;
}
download script
window.open('/api/controller/GetCsv', '_blank', '');
If you want to display csv content you can use the following code
[HttpPost]
public String GetCsv()
{
return exportRequests.GetCSV();
}
script
$('#btngetcsv').click(function() {
$.ajax({
url: "/api/controller/GetCsv",
data: {},
type: "Post",
dataType: "Json",
success: function(result) {
var arr = csvToArray(result);
for (var i = 0; i < arr.length; i++) {
var name = arr[i].name;
var lastname = arr[i].lastname;
//etc...........
}
},
error: function() {
}
});
});
function csvToArray(str, delimiter = ",") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function(row) {
const values = row.split(delimiter);
const el = headers.reduce(function(object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}

Event Not fire view to controller and not pass values in controller in mvc

I am sharing js code and controller code, when I enter values then I debug js code and show this values:
{"ReqID":"2","ReqNo":"000002","ReqDate":"21/09/2018","Job":"f","Approvedby":"f","IsApproved":"true","items":[{"Srno":"1","ItemCode":"018-0002","qty":"2","Remarks":"f"},{"Srno":"2","ItemCode":"028-0003","qty":"3","Remarks":"fff"},{"Srno":"3","ItemCode":"028-0010","qty":"7","Remarks":"ggg"}],"mSaveReq":"AddNew"}
but from the view to the controller the value is not passed, it only shows a js alert Error, I don't know what is the problem. The value passes correctly but why does this not pass the value to the controller?
Javascript
<script>
//Show model
function addNewOrder()
{
$("#NewOrderForm").modal();
}
// Add Multiple Record
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#ItemCode").val()) == "" || $.trim($("#Qty").val()) == "" || $.trim($("#Remarks").val()) == "") return;
var Srno = document.getElementById("detailsTable").rows.length;
ItemCode = $("#ItemCode").val(),
qty = $("#Qty").val(),
Remarks = $("#Remarks").val(),
detailsTableBody = $("#detailsTable tbody");
var ReqItems = '<tr><td>' + Srno + '</td><td>' + ItemCode + '</td><td>' + qty + '</td><td>' + Remarks + '</td><td> <a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(ReqItems);
clearItem();
});
//After Add A New Order In The List
function clearItem()
{
$("#ItemCode").val('');
$("#Qty").val('');
$("#Remarks").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove
$(document).on('click', 'a.deleteItem', function (e)
{
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "white").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveRequisition(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Home/RequisitionInsert", // function save
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveRequisition").click(function (e)
{
e.preventDefault();
var requisitionArr = [];
requisitionArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
requisitionArr.push({
Srno: $(this).find('td:eq(0)').html(),
ItemCode: $(this).find('td:eq(1)').html(),
qty: $(this).find('td:eq(2)').html(),
Remarks: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
ReqID: $("#ReqID").val(),
ReqNo: $("#ReqNo").val(),
ReqDate: $("#ReqDate").val(),
Job: $("#Job").val(),
Approvedby: $("#Approvedby").val(),
IsApproved: $("#IsApproved").val(),
items: requisitionArr,
mSaveReq: $("#mSaveReq").val()
});
$.when(saveRequisition(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
Controller
[HttpPost]
public ActionResult RequisitionInsert(string ReqID, string ReqNo,string ReqDate, string Job,string Approvedby,bool IsApproved, Requisition[] items, bool mSaveReq)
{
try
{
objclsRequisition.RequisitionInsert(ReqID, ReqNo,ReqDate, Job,Approvedby,IsApproved, items,mSaveReq);
ViewBag.Message = "Your record has been inserted Successfully";
ModelState.Clear();
return RedirectToAction("Requisition", "Home");
}
catch (Exception)
{
throw;
}
}
public int RequisitionInsert(string ReqID, string ReqNo, string ReqDate, string Job, string Approvedby, bool IsApproved, Requisition[] items, bool AddNew)
{
try
{
con.Open();
tr = con.BeginTransaction();
if (AddNew)
{
cmd = new SqlCommand("Select ISNULL(MAX(Req_ID), 0) + 1 from RequisitionMain", con);
ReqID = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("Select ISNULL(MAX(CAST(ReqNo as int)),0)+1 from RequisitionMain where Comp_ID=1 and GL_Year='2018-2019'", con);
ReqNo = cmd.ExecuteScalar().ToString().PadLeft(6, '0');
cmd = new SqlCommand("Sp_RequisitionMainInsert", con);
}
else
cmd = new SqlCommand("Sp_RequisitionMainUpdate", con);
cmd.Parameters.AddWithValue("#Req_ID", ReqID);
cmd.Parameters.AddWithValue("#ReqNo", ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#ReqDate", DateTime.Parse(ReqDate).ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#Job", Job);
cmd.Parameters.AddWithValue("#ApprovedBy", Approvedby);
cmd.Parameters.AddWithValue("#UserName", System.Web.HttpContext.Current.Session["AgentName"]);
cmd.Parameters.AddWithValue("#IsApproved", IsApproved);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
string mRowState = "";
for (int i = 0; i < items.Length; i++)
{
if(mRowState == "Deleted")
{
cmd = new SqlCommand("delete from RequisitionDetail where Req_ID_Det=" + items[i].Req_ID_Det + "", con);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
continue;
}
if (mRowState == "Added")
{
cmd = new SqlCommand("Select ISNULL(MAX(Req_ID_Det), 0) + 1 from RequisitionDetail", con);
Int64 mReqID_Det = Convert.ToInt64(cmd.ExecuteScalar());
cmd = new SqlCommand("Sp_RequisitionDetailInsert", con);
cmd.Parameters.AddWithValue("#Req_ID_Det", mReqID_Det);
}
else if (mRowState == "Modified")
{
cmd = new SqlCommand("Sp_RequisitionDetailUpdate", con);
cmd.Parameters.AddWithValue("#Req_ID_Det", items[i].Req_ID_Det);
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Req_ID", ReqID);
cmd.Parameters.AddWithValue("#ReqNo", ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#SrNo", i + 1);
cmd.Parameters.AddWithValue("#ItemCode", items[i].ItemCode);
cmd.Parameters.AddWithValue("#Qty", Convert.ToDecimal(items[i].Qty));
cmd.Parameters.AddWithValue("#Remarks", items[i].Remarks);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
tr.Commit();
return i;
}
catch (SqlException sqlex)
{
tr.Rollback();
throw sqlex; // read all sql error
}
catch (Exception ex)
{
tr.Rollback();
throw ex; // General execption
}
finally
{
con.Close();
}
}

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

Explanation of phantomjs code

I was asked to work on web crawler using phantomjs. However, as I read through the example, I was puzzled by some of the code:
Is this a loop? $("table[id^='post']").each(function(index)
What does this line of code mean? var entry = $(this);
How is the id captured? var id = entry.attr('id').substring(4);
This line var poster = entry.find('a.bigusername'); tries to get a username from the page. Is there a tutorial on how to make use of entry.find to scrap data off the page?
page.open(url1, function (status) {
// Check for page load success
if (status !== "success") {
console.log("Unable to access network");
phantom.exit(231);
} else {
if (page.injectJs("../lib/jquery-2.1.0.min.js") && page.injectJs("../lib/moment-with-langs.js") && page.injectJs("../lib/sugar.js") && page.injectJs("../lib/url.js")){
allResults = page.evaluate(function(url) {
var arr = [];
var title = $("meta[property='og:title']").attr('content');
title = title.trim();
$("table[id^='post']").each(function(index){
var entry = $(this);
var id = entry.attr('id').substring(4);
var poster = entry.find('a.bigusername');
poster = poster.text().trim();
var text = entry.find("div[id^='post_message_']");
//remove quotes of other posts
text.find(".quote").remove();
text.find("div[style='margin:20px; margin-top:5px; ']").remove();
text.find(".bbcode_container").remove();
text = text.text().trim();
var postDate = entry.find("td.thead");
postDate = postDate.first().text().trim();
var postUrl = entry.find("a[id^='postcount']");
if (postUrl){
postUrl = postUrl.attr('href');
postUrl = URL.resolve(url, postUrl);
}
else{
postUrl = url;
}
if (postDate.indexOf('Yesterday') >= 0){
postDate = Date.create(postDate).format('{yyyy}-{MM}-{dd} {HH}:{mm}');
}
else if (postDate.indexOf('Today') >= 0){
postDate = Date.create(postDate).format('{yyyy}-{MM}-{dd} {HH}:{mm}');
}
else{
var d = moment(postDate, 'DD-MM-YYYY, hh:mm A');
postDate = d.format('YYYY-MM-DD HH:mm');
}
var obj = {'id': id, 'title': title, 'poster': poster, 'text': text, 'url': postUrl, 'post_date' : postDate, 'location': 'Singapore', 'country': 'SG'};
arr.push(obj);
});
return arr;
}, url);
console.log("##START##");
console.log(JSON.stringify(allResults, undefined, 4));
console.log("##END##");
console.log("##URL=" + url);
fs.write("../cache/" + encodeURIComponent(url), page.content, "w");
phantom.exit();
}
}
});
Is this a loop? $("table[id^='post']").each(function(index)?
Yes
What does this line of code mean? var entry = $(this);
It assigns a jQuery object to variable entry
How is the id captured? var id = entry.attr('id').substring(4);
It uses jQuery which has attr() function.

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources