Trying to update div InnerHtml but nothing is happening - javascript

I have an html table on my webpage that is displaying data that I am pulling from a MySql database. When a user clicks on one of the table rows, depending on the data in the row, another div on the page is supposed to update displaying other information. The problem is, when I try to update the inner html of the div from my c# code-behind page, nothing happens. No errors in the dev console, no exceptions thrown, nothing. Why is this happening and how can I fix it? What am I doing wrong?
HTML table data that is being produced through c# code:
protected void PopulateUsers(bool active)
{
ArrayList userList = new ArrayList();
Query query = new Query();
StringBuilder userListHTML2 = new StringBuilder();
string userListHTML = "" +
"<table runat=\"server\" id=\"userListTable\" class=\"table table-striped table-bordered table-hover\">" +
"<thead>" +
"<tr>" +
"<th>User ID</th>" +
"<th>Name</th>" +
"<th>E-Mail</th>" +
"<th>Phone</th>" +
"<th>IsActive</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
string userListHTML3 = "" +
"</tbody>" +
"</table>";
switch (active)
{
case true:
userList = query.GetUserList(true);
break;
case false:
userList = query.GetUserList(false);
break;
}
foreach (User user in userList)
{
userListHTML2.Append(string.Format(#"
<tr>
<td>{0}</td>
<td>{1}</td>
<td>{2}</td>
<td>{3}</td>
<td>{4}</td>
</tr>", user.userID, user.displayName, user.email, user.phone, user.isActive));
}
userListDiv.InnerHtml = userListHTML + userListHTML2 + userListHTML3;
}
jQuery/javascript code capturing click:
function viewUserSpecifics(id) {
var data = id;
var xmlHttpRequest;
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("testing.XMLHTTP");
if (xmlHttpRequest == null) {
alert("ajax not supported");
return null;
}
xmlHttpRequest.open("GET", "ManagerPopup.aspx?ID=" + data, true);
xmlHttpRequest.send(null);
//document.getElementById('userDataDiv').innerHTML.
}
$(document).ready(function () {
$('#userListTable tbody').on('click', 'tr', function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
//$("#< %= userIDHidden.ClientID %>").val($.trim(tableData[0]));
//alert($.trim(tableData[0]));
viewUserSpecifics($.trim(tableData[0]));
return false;
});
});
Receiving the http request:
protected void Page_Load(object sender, EventArgs e)
{
PopulateUsers(true);
if (Request.QueryString["ID"] != null)
{
string ID = Request.QueryString["ID"];
SpecificUser(ID);
}
}
Method that is supposed to be updating div inner html:
protected void SpecificUser(string id)
{
System.Windows.Forms.MessageBox.Show(id);
Query query = new Query();
User specificUser = new User();
specificUser = query.GetUserSpecifics(Convert.ToInt32(id));
string newFormRow = "<div runat=\"server\" class=\"form-row\">";
string newFormGroup = "<div runat=\"server\" class=\"form-group\">";
string newFormGroupCol = "<div runat=\"server\" class=\"form-group col-md-6\">";
string closeDiv = "</div>";
string UserDataHTML1 = string.Format("" +
newFormRow +
"<label id=\"userIDLabel1\">User ID:</label>" +
"<label id=\"userIDLabel2\">{0}</label>" +
closeDiv +
newFormRow +
newFormGroupCol +
"<label id=\"lblFName\" for=\"txtFName\">First Name: </label>" +
"<input id=\"txtFName\" class=\"form-control\" runat=\"server\" type=\"text\" value={1} />" +
closeDiv +
newFormGroupCol +
"<label id=\"lblLName\" for=\"txtLName\">Last Name: </label>" +
"<input id=\"txtFName\" class=\"form-control\" runat=\"server\" type=\"text\" value={2} />" +
closeDiv +
closeDiv, id, specificUser.fName, specificUser.lName);
userDataDiv.InnerHtml = UserDataHTML1;
}
Any help would be greatly appreciated! Thanks!

To update the html content you should send back a response from your C# route to the client, and update the html part by using jQuery with received data

Related

Can't send value to Webservice from AJAX Call

Webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Colaborador GetUserInfo(int idColaborador)
{
bool Flag = true;
string constr = ConfigurationManager.ConnectionStrings["ControloInterno_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string[] Procedure = new string[] { "spOperadores", "spDetalhesColaborador", "spRegDrives" };
string[] ActionParams = new string[] { "SELECTINF", "SELECTUSR", "SELECTID" };
Colaborador co = new Colaborador();
Detalhes dt = new Detalhes();
Acesso ac = new Acesso();
for (int i = 0; Flag; i++)
{
using (SqlCommand cmd = new SqlCommand(Procedure[i]))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", ActionParams[i]);
cmd.Parameters.AddWithValue("#idColaborador", idColaborador);
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (Procedure[i] == "spOperadores")
{
while (rdr.Read())
{
co.Name = rdr["Nome"].ToString();
co.Department = rdr["Departamento"].ToString();
co.Profile = rdr["DescricaoPerfil"].ToString();
co.Name = rdr["Nome"].ToString();
co.Department = rdr["Departamento"].ToString();
co.Profile = rdr["DescricaoPerfil"].ToString();
co.AdminDate = rdr["dataadmin"].ToString();
co.Phone = rdr["tele"].ToString();
co.Status = rdr["status"].ToString();
co.Observations = rdr["Observacoes"].ToString();
co.CreationDate = rdr["DataCriacao"].ToString();
co.AltDate = rdr["AltData"].ToString();
co.Creator = rdr["criador"].ToString();
}
rdr.Close();
}
else if (Procedure[i] == "spDetalhesColaborador")
{
while (rdr.Read())
{
co.Detalhes = dt;
co.Detalhes.Description = rdr["Descricao"].ToString();
co.Detalhes.Value = rdr["Value"].ToString();
}
rdr.Close();
}
else if (Procedure[i] == "spRegDrives")
{
while (rdr.Read())
{
co.Acesso = ac;
co.Acesso.drive = rdr["Drive"].ToString();
co.Acesso.tipoAcesso = rdr["TipoAcesso"].ToString();
co.Acesso.nivel = rdr["nivel"].ToString();
Flag = false;
}
rdr.Close();
}
cmd.Parameters.Clear(); // Clear SQLCommand Parameters
con.Close();
}
}
return co;
}
}
and AJAX call
$(document).ready(function () {
$('#AdminUserNameModal').on('shown.bs.modal', function () {
var url = "GetColaboradoresWebService.asmx/GetUserInfo";
var ID = "15";
$("#UserInfoPanel").html("<div style='text-align:center; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
var request = $.ajax({
type: "POST",
url: url,
data: ID,
contentType: "application/json; charset-utf-8",
dataType: "json"
});
request.done(function (data) {
console.log(data);
var TableContent = "<table class='table table-bordered table-striped'>";
for (var i = 0; i < data.d.length; i++) {
TableContent += "<tr>" +
"<td>" + data.d[i].Name + "</td>" +
"<td>" + data.d[i].Detalhes.Description + "</td>" +
"</tr>";
"<tr>" +
"<td>" + data.d[i].Name + "</td>" +
"<td>" + data.d[i].Detalhes.Description + "</td>" +
"</tr>";
"<tr>" +
"<td>" + data.d[i].Name + "</td>" +
"<td>" + data.d[i].Detalhes.Description + "</td>" +
"</tr>";
}
TableContent += "</table>";
$("#UserInfoPanel").html(TableContent);
});
request.fail(function (data) {
console.log(data);
});
})});
I already searched everywhere and couldn't find anything that solved my problem. I tried recieve a string too and nothing. I keep getting conversion to int or string errors, I don't understand, I'm trying to send a string and recieve a string, or int to int and still gives me an error? In the code I'm sending a string and recieving an int but i was just changing the code again.
Problem solved, the correct way was to treat everything as a string like this++
data: "{idColaborador: " + idColaborador + " }",
var idColaborador = 15
try this instead , why are you sending a string to a method that accepts an int as a parameter ?
Edit :
your property names must match the name of the parameter on the method so they can be bound appropriately like i changed above , this will work
data:{idColaborador:ID}

Unable to pass C# string variable to JavaScript file

What I am trying to do currently is pass a JSON string from the back-end C# to JavaScript to populate the drop down lists. What currently is happening is that when I use the information from the link provided, all i get in return is a literal output of ""<%= jsonFoodString %>". I do not understand why it is doing that. If someone can point me in the correct direction that would be great.
The current post I have been looking at:
Passing variable from ASP.net to JavaScript
The way I have been trying is (Example):
C# Code:
protected string jsonFoodString { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:63591/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Meals/").Result;
if (response.IsSuccessStatusCode)
{
string foods = response.Content.ReadAsStringAsync().Result;
jsonFoodString = foods;
BindData();
}
}
}
Javascript:
var count = 1;
$(document).ready(function() {
$("#addItemButton").click(function() {
if (count <= 5) {
$("#ContentPlaceHolder1_AddMealContainer")
.append(
$("<div class=\"form-group\" id=\"MealItem_\"" +
count +
">" +
"<div class=\"row\">" +
"<label ID=\"AddItemLabel_1\" class=\"col-xs-4 control-label\">Item</label>" +
"<div class=\"col-xs-4\">" +
"<select ID =\"AddItemDropdownList_1\" data-html=\"true\" data-animation=\"true\" data-toggle=\"tooltip\" data-placement=\"top\" class=\"form-control\">" +
"</select>" +
"<div class=\"has-error\">" +
"<span class=\"help-block\">" +
"</span>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
);
count++;
var notParsedFoodString = "<%= jsonFoodString %>";
console.log(notParsedFoodString); //Produces a literal string of "<%= jsonFoodString %>"
} else {
alert("You can only add 5 food items to a meal");
}
});
$("#addItemButton").append("<input type=\"button\" value=\"Add Food Item\" id=\"AddMealItem\" class=\"btn btn-default btn-sm\">");
});
I found the answer I was looking for here!
XMLHttpRequest is deprecated. What to use instead?
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log(this.status) // do something; the request has completed
}
}
xhr.open("HEAD", "http://example.com") // replace with URL of your choosing
xhr.send()

how to insert dynamic multiple rows textboxes generated value in a variable

I'm trying insert dynamic multiple rows textboxes generated value in a variable to send it through ajax json to server side.
Code for generating multiple dynamic values.
$('#btnASize').click(function() {
var sizerangeMin = "<input type='text' ID='SizeMin' value='2.00' />";
var ToleranceMin = "<input type='text' ID='TolMin'+i value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax'+i value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnASizeR').click(function() {
var sizerangeMin = "<input type='text' ID='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
Ajax code for sending data
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function() {
$(document).on("click", "[id*=btnFrmSubmit]", function() {
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({
user: user
})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function(response) {
alert(response.responseText);
}
});
});
});
</script>
In the above ajax method i want to store values of dynamically generated multiple textboxes value in "var user" to send it through ajax method to server side but not getting any idea how to achieve it i have shown in above code only for a particular input box
"<th class='text-center'>TDC No.</th>" +
"<th><input id='Tdc_No' type='text' value='7y'/></th>".
how to achieve it for multiple dynamically generated input textboxes.
Code at server side i am just showing few items how am i doing.
public class User
{
public decimal PRODUCT_ID { get; set; }
public string TDC_NO { get; set; }
.
.
}
[WebMethod]
public static void SaveFrmDetails(User user)
{
string connectionString = ConfigurationManager.ConnectionStrings["condb"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TDC_PRODUCT1(TDC_NO) VALUES (:TDC_NO)",con)
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(":TDC_NO", user.TDC_NO);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
try like this , make use of .serializeArray() and find()
$( "#target" ).click(function() {
alert(JSON.stringify($("#WireDimTbl tbody").find(":input").serializeArray()));
});
jsfiddle working : https://jsfiddle.net/pranayamr/odja5te0/

javascript get selected value from form (in Netbeans web project with DB)

I need little help.
First, I have page with some values from Database in form, like this:
out.println("<form method=\"post\" action=\"update.jsp?id=" +
rs.getString(1) +"\" onSubmit=\"return editF(this)\" id=\"editDiv"+ rs.getString(1) +"\" >" + SelectCat() +" </form>")
public String SelectCat()
{
String result = "<select name=\"category\" >";
try
{
String request = "SELECT * FROM cat";
Statement st = getConnection().createStatement();
ResultSet rs = st.executeQuery(request);
while (rs.next())
{
result += "<option value=\"" + rs.getString(1) + "\">" + rs.getString(2) + "</option>";
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
result += "</select>";
return result;
}
And my javascript function is
function editF(form)
{
alert("a");
string header = form.header.value;
string text = form.text.value;
string category = form.category.selectedIndex.value;
var e = document.getElementByName("category");
//var category = e.selectedIndex;
form.action = form.action + "&header="+header+"&text="+text+"&categoryID="+category;
return true;
};
But I can't get selected value.
Can you help me?
Thanks!
var category = form.category.options[ form.category.selectedIndex ].value;
Also, javascript is not a strongly-typed language, you cannot define its type when declaring it. Instead, use var.

How update data by Javascript

How can I, on the OnChange event, update data in my database ?
I have a WebMethod, that returns a HTML, so I can't see those elements, so I think he solution will be a javascript function.
A textarea catch the text from the database, if the user alter this, the database field has to be updated.
[WebMethod]
public static object ListAdvertise(string transaction)
{
StringBuilder retorno = new StringBuilder(160000);
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
string Credenciada = tk2.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value);
string select3 = "SELECT * FROM San_Imovel WHERE Status_Id = 1 AND Credenciada_Id = " + Credenciada + " AND Transacao_Id IN (" + transacao + ") ORDER BY NomeCidade, NomeBairro, Imovel_Id ASC";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
Imovel_Id = r3["Imovel_Id"].ToString();
Endereco = r3["Descricao"].ToString() + " " + r3["Logradouro"].ToString() + " " + r3["Numero"].ToString() + "/" + r3["DscComplemento"].ToString() + " " + r3["Complemento"].ToString() + " - " + r3["NomeBairro"].ToString();
TextoAnuncio = r3["TextoAnuncio"].ToString();
if (count % 2 == 0)
{
classe = "EstiloDalinhaGrid";
}
else
{
classe = "EstiloDalinhaAlternativaGrid";
}
retorno.Append("<tr class='" + classe + "'>");
retorno.Append("<td>");
retorno.Append(Imovel_Id);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append(Endereco);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<textarea id='txtArea'>");
retorno.Append(TextoAnuncio);
retorno.Append("</textarea>");
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<input type='checkbox' class='imoveisMarcados' id='" + Imovel_Id + "' />");
retorno.Append("</td>");
retorno.Append("</tr>");
count++;
}
retorno.Append("</table>");
con3.Close();
return new
{
retorno = string.Format(retorno.ToString())
};
i think you have to use Ajax for you to be able to update your data base .
check this link to learn more about ajax with Php (you chose whatever server side langage you'd like)
Ajax with PHP

Categories