I want to display image from my database which stores the path to the image's location. Following code gives me the image path only in the output. What changes do I need to make in order for image to appear instead of image path?
GetBusinessCategoryList: function () {
debugger;
var data = JSON2.stringify({
});
$.ajax(
{
contentType: "application/json; charset=utf-8",
type: 'POST',
url: 'http://localhost:44719/Modules/BusinessCategoryView/Service/BusinessCategoryWebService.asmx/GetAllBusinessCategory',
dataType: 'json',
data: data,
success: function (result) {
alert("ok");
var returnedData = result;
BusinessManagement.BindBusinessCategoryList(returnedData);
},
error: function (error) {
alert("error");
}
});
},
BindBusinessCategoryList: function (data) {
debugger;
var cLst = data.d;
if (cLst.length > 0) {
headElements += '<table id="customerTable" cellspacing="0" cellpadding="0" >';
headElements += '<thead class="sfHeadingone">';
headElements += '<tr><th align="left">Category Image</th>';
;
headElements += '</thead>';
$('#tblGrid').html(headElements);
var i = 0;
if (i === 0) {
bodyElements += '<tbody>';
}
$.each(cLst, function (index, value) {
bodyElements += "<td>" + value.CategoryImage + "</td>";
}
});
Use img to display an image. Pass the image url to the src attribute of the img tag
bodyElements += "<td><img src='" + value.CategoryImage + "'></td>";
Related
I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}
I'm trying to pass two arguments to the Authorization.js file. It is used to search in the variables that I sent from Index.cshtml file.
Here at the end of the Index.cshtml file
<script src="~/AreasFolder/Authorization/js/Authorization.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var fork = '#Html.Raw(Json.Serialize(new ImOnTech.Hukuk.Web.Repository.RoleTreeRepository(_configuration).TaskItemRolsuzGetir()))';
sayfaGruplariArray = JSON.parse(fork);
var exec = '#Html.Raw(Json.Serialize(new ImOnTech.Hukuk.Web.Helpers.UserHelper(_roleManager).GetRoles()))';
rollerArray = JSON.parse(exec);
$("#sayfaAraTable").toggle(false);
$('#sayfaAraTextbox').keyup(function () {
sayfalariFiltrele(true);
});
$("#sayfaGrubuAraTable").toggle(false);
$('#sayfaGrubuAraTextbox').keyup(function () {
sayfaGruplariniFiltrele(true);
});
$("#kullaniciAraTable").toggle(false);
$('#kullaniciAraTextbox').keyup(function () {
kullanicilariFiltrele(true);
});
$("#rolAraTable").toggle(false);
});
In the controller, string ItemName returns NULL from Authorization.js:
Finaly, Authorization.js file:
var sayfaGruplariArray;
var rollerArray;
function sayfalariFiltrele(isAutoComplete) {
var content = $('#sayfaAraTextbox').val();
if (content.length == 0 && isAutoComplete) {
$("#sayfaAraTable").toggle(false);
//$("tr:not(:first)", "#sayfaAraTable").remove();
}
else {
//$("tr:not(:first)", "#sayfaAraTable").remove();
$.ajax({
url: "/Authorization/Item/SayfaAra",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
itemName: content
}),
beforeSend: function (xhr) {
//jQuery.blockUI({ message: 'Lutfen bekleyiniz', baseZ: 2000 });
$('#sayfaAraTextbox').addClass('textboxLoadinggif');
},
success: function (result) {
if (result.ErrorCode == "0") {
$("#sayfaAraTable").toggle(true);
var html = "";
var sayfalarArray = result.SayfaListesi;
if (sayfalarArray.length > 0) {
html += "<tr>";
html += "<th>İşlem adı</th>";
html += "<th>Açıklama</th>";
html += "<th>URL</th>";
html += "<th>Menüde görünsün</th>";
html += "<th style='width:1%'></th>";
html += "</tr>";
}
for (i = 0; i < sayfalarArray.length; i++) {
html += "<tr id='sayfaTr" + sayfalarArray[i].AuthorizationItemKey + "'>";
html += "<td>" + sayfalarArray[i].ItemName + "</td>";
html += "<td>" + sayfalarArray[i].Description + "</td>";
html += "<td>" + sayfalarArray[i].MenuLinkUrl + "</td>";
html += "<td>" + sayfalarArray[i].DisplayInMenu + "</td>";
html += "<td nowrap><a href=\"javascript:SayfaBilgisiniGetir(" + sayfalarArray[i].AuthorizationItemKey + ")\"title='Güncelle'><i class='fa icon-pencil fa-2x'></i></a> <a href='javascript:SayfaSilUyari(" + sayfalarArray[i].AuthorizationItemKey + ")' title='Sil'><i class='fa icon-trash fa-2x'></i></a></td>";
html += "</tr>";
}
//$("#sayfaAraTable").append(html);
$("#sayfaAraTable").html(html);
}
else {
$("#sayfaAraTable").toggle(false);
toastr.warning(result.Result, "Uyarı", { timeOut: 3000 });
}
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
},
failure: function (xhr, ajaxOptions, thrownError) {
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
$("#sayfaAraTable").toggle(false);
toastr.error("script failure: " + xhr.responseText, "Uyarı", { timeOut: 3000 });
},
error: function (xhr, ajaxOptions, thrownError) {
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
$("#sayfaAraTable").toggle(false);
toastr.error("script error: " + xhr.responseText, "Uyarı", { timeOut: 3000 });
}
});
}
}
Any idea? What cause this problem? Thank you in advance.
You should use [FromBody] to get the json format data. Change it like below:
$.ajax({
//...
contentType: "application/json; charset=utf-8",
data: JSON.stringify(content),
//...
})
Controller:
public ActionResult SayfaAra([FromBody]string itemName)
I'm trying to make loading appear before making a request using ajax and even then the screen is only locked.
JS:
function showEstoque(productId) {
if (url !== '' && url != '-1') {
if (active) {
hideEstoques(active);
}
var target = document.getElementById("productInfo" + productId);
target.innerHTML = generateRows(productId);
target.style.display = "block";
active = productId;
}
}
function hideEstoques(productId) {
document.getElementById("productInfo" + productId).style.display = "none";
active = null;
}
function generateRows(productId) {
var rows = '';
rows += generateRowsEstoque(productId);
rows += generateRowsReserva(productId);
return rows;
}
function generateRowsEstoque(productId) {
var textContent = searchE(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse[0].nothing : null;
if (!data)
return '<span>Nothing</span><table><tr><td>Nothing</td></tr></table>';
var rows = '<span>Nothing</span> <table><thead> <tr> <th>Nothing</th></tr> </thead> <tbody>';
for(var n=0; n < data.length; n++) {
rows += '<tr>' +
'<td>' + data[n].nothing + '</td>' +
'</tr>';
}
rows += '</tbody> </table>';
return rows;
}
function searchE(productId) {
var view_data = "[]";
jQuery.ajax({
url: url + "product/" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function generateRowsReserva(productId) {
var textContent = searchEReserva(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse : null;
if (!data)
return '<table class="info"><tr><td class="none">Nothing</td></tr></table>';
var foo = data.filter(function(p) { return p.idType === 'foo' });
var bar = data.filter(function(p) { return p.idType === 'bar' });
var fooQtd = foo.length ? foo[0].nothing : 0;
var barQtd = bar.length ? bar[0].nothing : 0;
var rows = '<br/><table class="info"><thead> <tr class="labels"> <th>Nothing</th> </tr> </thead> <tbody>';
rows += '<tr>' +
'<td>' + fooQtd + '</td>' +
'<td>' + barQtd + '</td>' +
'</tr>';
rows += '</tbody> </table>';
return rows;
}
function searchEReserva(productId) {
var view_data = "[]";
$j.ajax({
url: "url" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function startLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "";
}
}
function stopLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "none";
}
}
HTML:
<td
onclick="showEstoque(1);">
<div id="estoque_1" class="estoqueCor st-color_"/>">1</div>
<img id="imgEstoqueProduto"
style="vertical-align: middle; display: none;"
src="<c:url value="/images/ajaxLoader.gif"/>">
<div class="container-product-info">
<div onmouseout="hideEstoques(1);"
class="productInfo"
id="productInfo1"></div>
</div>
</td>
I tried to use the beforeSend, call before the ajax method starts, ajaxStart and even then it doesn't work and the screen just hangs. Could you help me please?
I called startLoading before everything and it still doesn't work
I removed async: false but, I need to wait for the data to be returned from the API
I’m trying to update values in a table pulled in from MySQL but the function is not re-running?
Alternatively, if there is another solution to allow me to update the values from the MySQL database on a 60 second interval please let me know.
EDIT: error has been resolved but now i get a new error instead of replacing the mysql value in the table cell it adds new cells into the table what part of the code would need to be changed or added to resolve this?
The code below returns no errors:
<script type="text/javascript">
$(document).ready(function(){
console.log(1+0);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
setInterval(updateTable, 10000);
}
})
})
function updateTable() {
console.log(1+1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
};
</script>
If you format it well you'll see that youre setInterval is inside your function...
You sould place it in the $(document).ready callback function.
$(document).ready(function () {
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
// <===== You should place youre set interval here
}
})
});
function updateTable() {
console.log(1 + 1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
var updateTableInterval = setInterval(updateTable, 10000);
}
It looks like you are calling setInterval(updateTable) from inside updateTable.
You're not calling updateTable from anywhere outside of updateTable, which means the function is never running, and the setInterval is never executed.
To fix, either:
Put your setInterval outside of updateTable, or
Add updateTable() to the end of your script.
I recommend the former.
Instead of using setInterval,
setInterval(updateTable, 10000);
try using setTimeout after you process and update the table:
function updateTable() {
$.ajax({
...
,complete: function(data){
// do something
setTimeout(updateTable, 10000);
...
});
}
This will allow your code to wait for the information to arrive prior to make another request and not be considered a DoS attack.
Let me know if this works for you or not. We can try something else.
Let suppose i have a json file
and i can read this file in my script like this
$(document).ready(function () {
$.ajax({
type: "GET",
url: "Package.html",
dataType: "json",
success: function (data) {
var t = '';
for (var i = 0; i < data.yearData.length; i++) {
var mainStoryTitle = data.yearData[i].players;
for (var j = 0; j < mainStoryTitle.length; j++) {
var storyTitle = mainStoryTitle[j].name;
var topStoryContent = mainStoryTitle[j].description;
var storyImage = mainStoryTitle[j].image;
t = t + '<div class="content">';
t = t + '<article class="topcontent">';
t = t + '<header class="top" id="top1"><h2>' + storyTitle + '</h2></header>';
t = t + '<header class="bottom">';
t = t + '<h6><img src="' + storyImage + '" height=150 width=200>' + '</h6></header>';
t = t + '<content class="hide" id="content_' + j + '"><p>' + topStoryContent + '</p></content>';
t = t + '</article>';
t = t + '</div>';
}
}
$(".content").html(t);
},
error: function (e, ts, et) { alert(ts) }
})
});
and then i put this script in my html file.
So when i run this, it works properly but the problem is when i click on view source then inside it shows the path of json instead of exact data.
Hope you got the problem and please revert me asap.thanx
Instead of using alert, use console.log(ts) this will post the JSON file into your console. From there you can easily look around and see the JSON file by clicking the down arrow.
console.log(data); shows as:
> Object {Data: Array[2], ResponseMessage: "", Success: true}
console.log(JSON.stringify(data)); shows as:
{"Data":[{"ControllerID":2,"Description":"Aeon Power Monitor","DevType":1,"ID":1,"Name":"Power Monitor"},{"ControllerID":2,"Description":"Aeon Power Switch","DevType":2,"ID":2,"Name":"Switch"}],"ResponseMessage":"","Success":true}