display image using jquery and ajax - javascript

To display company details with image,
I have controller like:
public JsonResult PrintHeading()
{
CompanyModel cm = new CompanyModel();
string qry = "select CompanyName,Address,ContactNo,EmailAddress,LogoFileName from tblCompanyInfo";
DataTable dt = cls.LoadData(qry);
foreach (DataRow dr in dt.Rows)
{
cm.CompanyName = Convert.ToString(dr["CompanyName"]);
cm.Address = Convert.ToString(dr["Address"]);
cm.ContactNo = Convert.ToString(dr["ContactNo"]);
cm.EmailAddress = Convert.ToString(dr["EmailAddress"]);
cm.LogoFileName = Path.Combine("\\Content\\Logo", Convert.ToString(dr["LogoFileName"]));
}
return Json(cm, JsonRequestBehavior.AllowGet);
}
and Function:
function getPrintHeading() {
var heading = '';
$.ajax({
url: '#Url.Content("~/Bank/PrintHeading")',
type: "GET",
dataType: "JSON",
async: false,
success: function (headdata) {
heading = '<img src="' + headdata.LogoFileName + '" width=50 height=50>' + headdata.CompanyName + '<br>' + headdata.Address + '<br>' + headdata.ContactNo + ', ' + headdata.EmailAddress ;
}
});
return heading;
}
It displays all other data but doesn't display image.please Can you give the idea?

I think you forgot to close img tag.Check it once may help You.
<img src="' + headdata.LogoFileName + '" width=50 height=50 />

Related

Passing List String from C# to JavaScript

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;
}
}

Web API Controller POST & PUT & DELETE not working correctly

I keep getting results as false when running my POST & PUT & DELETE methods.
When I used POSTMAN I get 200 OK but my response returns as false?
Here's what I get when i use POST:
https://i.stack.imgur.com/fytB1.png
Here's what I get when i use UPDATE:
https://i.stack.imgur.com/y3vdv.png
Here's what I get when i use DELETE:
https://i.stack.imgur.com/hSNjy.png
Here is my controller code:
[HttpPost("AddNewOwner")]
public Boolean AddNewOwner(Owner theOwner)
{
DBConnect objDB = new DBConnect();
string strSQL = "INSERT INTO HomeOwnership_T (HomeOwnerID, FirstName, LastName, Address, City, State, ZipCode, TelNo, Email, BlockNo, LotNo, SaleDate, SalePrice, IsSold) " +
"VALUES ('" + theOwner.HomeOwnerID + "', '" + theOwner.FirstName + "', '" +
theOwner.LastName + "', '" + theOwner.Address + "', '" + theOwner.City +
"', '" + theOwner.State + "', '" + theOwner.ZipCode + "', '" + theOwner.TelNo + "', '"
+ theOwner.Email + "', '" + theOwner.BlockNo + "', '" + theOwner.LotNo + "', '"
+ theOwner.SaleDate + "', '" + theOwner.SalePrice + "', '" + theOwner.IsSold + "')";
//Execute the INSERT statement in the database
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
string command = "SELECT TOP 1 HomeOwnerID FROM HomeOwnership_T ORDER BY DESC";
DataSet ds = objDB.GetDataSet(command);
Tax taxInfo;
foreach (DataRow record in ds.Tables[0].Rows)
{
taxInfo = new Tax();
taxInfo.HomeOwnerID = int.Parse(record["HomeOwnerID"].ToString());
string strSQL2 = "INSERT INTO TaxInfo_T (AccessedVal, LandVal, AdditionalVal, TaxRate, TaxPerYear, RealEstateTax, HomeOwnerID)"
+ "VALUES (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '" + taxInfo.HomeOwnerID + "')";
objDB.DoUpdate(strSQL2);
}
return true;
}
else
{
return false;
}
}
[HttpPut]
public Boolean Update(Owner theOwner)
{
DBConnect objDB = new DBConnect();
HomeTax owner = new HomeTax();
string strSQL = "UPDATE HomeOwnership_T SET HomeOwnerID = " + theOwner.HomeOwnerID +
", FirstName = '" + theOwner.FirstName + "', LastName: '" + theOwner.LastName +
"', Address = '" + theOwner.Address + "', City = '" + theOwner.City +
"', City = '" + theOwner.City + "', State = '" + theOwner.State +
"', ZipCode = '" + theOwner.ZipCode + "', TelNo = '" + theOwner.TelNo +
"', Email = '" + theOwner.Email + "', BlockNo = " + theOwner.BlockNo +
", LotNo = " + theOwner.LotNo + "', SaleDate = '" + theOwner.SaleDate +
"', SalePrice = " + theOwner.SalePrice + ", IsSold = '" + theOwner.IsSold +
" WHERE HomeOwnerID = " + theOwner.HomeOwnerID;
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
return true;
}
else
{
return false;
}
}
[HttpDelete("{id}")]
public Boolean Delete(int id)
{
DBConnect objDB = new DBConnect();
string strSQL = "DELETE * FROM HomeOwnership_T INNER JOIN TaxInfo_T " +
"ON HomeOwnership_T.HomeOwnerID = TaxInfo_T.HomeOwnerID WHERE HomeOwnerID = " + id;
int result = objDB.DoUpdate(strSQL);
if(result > 0)
{
return true;
}
else
{
return false;
}
}
Here are my ajax calls:
$(document).on("click", "#btnAddHomeOwner", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/AddNewOwner";
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("btnAddHomeOwner selected");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
// Make an AJAX request to get a home and store the response in the appropriate div.
$.ajax({
type: "POST",
url: strURL,
contentType: "application/json", // set the data type sent to the Web Service.
dataType: "json", // set the data type expected from the Web Service.
data: strInput, // send an empty JSON object (no input required).
success: function (data) { // set callback function used to update the page/
console.log(data);
var result = data;
if (result == true)
$("#msg").text("The record was successfully added to the database.");
else
$("#msg").text("The record was not added to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnStoreHomeOwner click event
$(document).on("click", "#btnDelete", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/";
var param = $("#txtHomeOwnerID").val();
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Delete button selected.");
$.ajax({
type: "DELETE",
url: strURL + param,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{5}",
success: function (data) {
console.log(data);
var result = data;
if (result == true) {
$("#msg").text("The record with HomeOwnerID: " + param + " was deleted.");
alert("Deleted!");
}
else {
$("#msg").text("The record with HomeOwnerID: " + param + " was not deleted.");
alert("Not Deleted");
}
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnDelete click event
$(document).on("click", "#btnUpdateAll", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/Update";
// Clear the divs contents.
//$("#display").html("");
//$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Update home owner button selected.");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
//Make an AJAX request to get a home owner and display the response in the appropriate div
$.ajax({
type: "PUT",
url: strURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: strInput,
success: function (data) {
console.log(data);
var owner = data;
$("#display").html("<hr><p>".concat("HomeOwnerID: ", owner.HomeOwnerID,
"<br>FirstName: ", owner.FirstName, "<br>LastName: ", owner.LastName,
"<br>Address: ", owner.Address, "<br>City: ", owner.City,
"<br>State: ", owner.State, "<br>ZipCode: ", owner.ZipCode,
"<br>Telephone Number: ", owner.TelNo, "<br>Email: ", owner.Email,
"<br>Block Number: ", owner.BlockNo, "<br>Lot Number: ", owner.LotNo,
"<br>Date of Sale: ", owner.SaleDate, "<br>Sale Price: $", owner.SalePrice,
"<br>Sold Status: ", owner.IsSold, "<br>Accessed Value: $", owner.AccessedVal,
"<br>Land Value: $", owner.LandVal, "<br>Additional Value: $", owner.AdditionalVal,
"<br>Tax Rate: $", owner.TaxRate, "<br>Tax Per Year: $", owner.TaxPerYear,
"<br>Real Estate Tax: $", owner.RealEstateTax, "</p >"));
if (owner == true)
$("#updateResult").text("The record was successfully updated to the database.");
else
$("#updateResult").text("The record was not updated to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); //end of btnUpdate
check your sql string when you set the homeownerid is it suppose to be "SET hoID = '" + theOwner.HomeOwnerID + "', ownerName = '" + theOwner.ownerName + "'....etc

How to submit multiple values using ajax and django

Question I want to be able to submit multiple records with my ajax form submission. This form is a partial and I want to be able to submit multiples of this form each time. This is what I have so far I can't get my textbox.vals anymore using a serialized string. Any help would be greatly appreciated.
Here is my function
function SaveDim() {
$.ajax({
type: "POST",
url: "/sheet/sheet_form_create.html/_dim",
//dataType: "json",
data: $('#form').serialize()
+
"&description=" + $('#id_description').val() +
"&style=" + $('#id_style').val() +
"&target=" + $('#id_target').val() +
"&upper_limit=" + $('#id_upper_limit').val() +
"&lower_limit=" + $('#id_lower_limit').val() +
"&inspection_tool=" + $('#id_inspection_tool').val() +
"&critical=" + $('#id_critical').val() +
"&units=" + $('#id_units').val() +
"&metric=" + $('#id_metric').val() +
"&target_strings=" + $('#id_target_strings').val() +
"&ref_dim_id=" + $('#id_ref_dim_id').val() +
"&nested_number=" + $('#id_nested_number').val() +
"&posistion=" + $('#id_position').val() +
"&met_upper=" + $('#id_met_upper').val() +
"&met_lower=" + $('#id_met_lower').val() +
"&valc=" + $('#id_valc').val() +
"&sheet_id=" + $('#id_sheet_id').val() +
"",
success: function (json) {
console.log(json);
alert(json);
}
});
}
Here is my add_dimension method in views.py
def add_dimensions(request):
if request.method == 'POST':
c_date = datetime.now()
u_date = datetime.now()
description = request.POST.get('description')
style = request.POST.get('style')
target = request.POST.get('target')
upper_limit = request.POST.get('upper_limit')
lower_limit = request.POST.get('lower_limit')
inspection_tool = request.POST.get('inspection_tool')
critical = request.POST.get('critical')
units = request.POST.get('units')
metric = request.POST.get('metric')
target_strings = request.POST.get('target_strings')
ref_dim_id = request.POST.get('ref_dim_id')
nested_number = request.POST.get('nested_number')
met_upper = request.POST.get('met_upper')
met_lower = request.POST.get('met_lower')
valc = request.POST.get('valc')
sheet_id = request.POST.get('sheet_id')
data = {}
dim = Dimension(
description=description,
style=style,
target=target,
upper_limit=upper_limit,
lower_limit=lower_limit,
inspection_tool=inspection_tool,
critical=critical,
units=units,
metric=metric,
target_strings=target_strings,
ref_dim_id=ref_dim_id,
nested_number=nested_number,
met_upper=met_upper,
met_lower=met_lower,
valc=valc,
sheet_id=sheet_id,
created_at=c_date,
updated_at=u_date)
dim.save()
data['description'] = dim.description;
data['style'] = dim.style;
data['target'] = dim.target;
data['upper_limit'] = dim.upper_limit;
data['lower_limit'] = dim.lower_limit;
data['inspection_tool'] = dim.inspection_tool;
data['critical'] = dim.critical;
data['units'] = dim.units;
data['metric'] = dim.metric;
data['target_strings'] = dim.target_strings;
data['ref_dim_id'] = dim.ref_dim_id;
data['nested_number'] = dim.nested_number;
data['met_upper'] = dim.met_upper;
data['met_lower'] = dim.met_lower;
data['valc'] = dim.valc;
data['sheet_id'] = dim.sheet_id;
return HttpResponse(json.dumps(data), content_type="application/json",)
else:
dim_form = DimForm()
return render(request, 'app/_dim.html', {'dim_form': dim_form})
Just do it this way
function SaveDim() {
$.ajax({
type: "POST",
url: "/sheet/sheet_form_create.html/_dim",
//dataType: "json",
//make sure you give your form an id of "dim_form"
data: $('#dim_form').serialize()
success: function (json) {
console.log(json);
alert(json);
}
});
}
You need to concat correctly your data string like:
data: $('#form').serialize() + "&description=" + $('#id_description').val() + "&style=" + $('#id_style').val(); // ...

.empty() function won't work after loading contents with ajax

I did a multilevel ajax call .i.e. make an ajax call and use the id value from the call to make another call... I tried calling a jquery .empty() isn't working for the data generated in the inner ajax call... But when i place the .empty() function on the outer generated element, it worked just fine... How can i fix this issue? This is my code../
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({ //first ajax call///
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output) {
if (output.result === 'success') {
$('.blog').empty();
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var storyTitle = this.story_view;
var frontTitle = '<div class="blog-item"><h3>' + storyTitle + '</h3>' + '<img class="img-responsive img-story" src="images/blog/blog1.jpg" width="100%" alt="" />' + '<div class="blog-content"><div class="entry-meta"><h4>Episodes</h4></div>' + '<div class="well" style="padding-right: 10px; padding-left: 5px; width: 105%;">' + '<ul class="tag-cloud stories">';
var request2 = $.ajax({ ////inner ajax call//////
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function(output2) {
var i = 1;
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
var title = this.title;
var count = this.episode_count;
if (count == 0) {
frontTitle += id2;
} else if (i % 20 == 0) {
frontTitle += '<li data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li></ul><ul class="tag-cloud">';
} else {
frontTitle += '<li style="margin: 1px" data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li>';
}
i += 1;
})
}
$('.blog').append(frontTitle);
frontTitle += '</ul></div></div>';
})
})
} else {
console.log('failed');
}
});
});
I really need help for this, i av been on this for two days now... I would really appreciate the help.. or is there a better way i could do this?

How to pass values to asp pages from javascript?

I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}

Categories