DataSet Value in Jquery C# - javascript

I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}

So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help

Related

AJAX Call to Update table goes Null - ASP.NET

I'm trying to update my table using Ajax Call through this code
var customer = {};
customer.CustomerId = row.find(".CustomerId").find("span").html();
customer.Nome = row.find(".Nome").find("span").html();
customer.Tipo = row.find(".Tipo").find("span").html();
customer.NCM = row.find(".NCM").find("span").html();
customer.Contabil = row.find(".Contabil").find("span").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
But when I click to update the value it returns a System.NullReferenceException, I can't see where I'm doing wrong.
Here's my Controller Code
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
entities.SaveChanges();
}
return new EmptyResult();
}
System.NullReferenceException revealed the value updatedCustomer or customer is null.You need check which is null.
And when you want to update a enity in EF,you need add code like :
context.Entry(existingBlog).State = EntityState.Modified;
Howerver,Why you need Query A Entity befor update?I guess you want to do this:
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Entry(customer).State = EntityState.Modified;
entities.SaveChanges();
}
return new EmptyResult();
}
This AJAX callback below actually passed JSON string containing JSON object, which is wrong and causing customer contains null value which throwing NullReferenceException (it is strongly advised to put null check before using EF entity context):
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}', // this is wrong
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Instead of passing JSON string like that, just use data: JSON.stringify(customer) or simply passing entire object directly with data: customer and remove contentType setting:
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: customer,
dataType: "json",
success: function (result) {
// do something
}
});
Regarding second issue which selected data from table query is not updated, it depends on auto-tracking setting from EF. If auto-tracking is disabled, you need to set EntityState.Modified before using SaveChanges():
if (customer != null)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
// if EF auto-tracking is disabled, this line is mandatory
entities.Entry(updatedCustomer).State = System.Data.Entity.EntityState.Modified;
entities.SaveChanges();
}
}
Notes:
1) You can see all methods to update existing data with EF in this reference.
2) This fiddle contains sample to make AJAX request from a table contents.

Get JSON array data by field name

I'm trying to get JSON data by field name like this data.name and it return the desired data, but I have 25 fields in the array and I want to make this dynamically, using data + "." + variable, when I alert it returns [Object object].name, so how I can make it executable?
I tried many ways but all failed, please help me doing this.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: {
'Arrnagement': Arrnagement
},
success: function(data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = data[0].jid;
alert(resulting);
if (result[i].innerHTML = data[0].jid != "undefined") {
result[i].innerHTML = data[0].jid;
} else {
result[i].innerHTML = "";
}
}
//jid = name;
//data[0].name returns "Joun"
//data[0]+"."+jid returns [object object].name but i need it to return "Joun"
This should work. I changed the dot notation while accessing the object property.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: { 'Arrnagement': Arrnagement },
success: function (data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var responseData = data[0];
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = responseData[jid];
alert(resulting);
if (responseData[jid]) {
result[i].innerHTML = responseData[jid];
}
else {
result[i].innerHTML = "";
}
}
Try giving data[0][jid], we can give a variable in brackets also inorder to get the data
Hope it works
If do foo.bar you are getting a property with the name 'bar' on object foo. If you have some variable const bar = "qux" and you want to access property on some object with the same name as bar value /"qux"/ you just need to use square brackets - foo [bar], which will be the same as calling foo.qux; So, in your case you just need to use data[0][jid] instead of data [0].jid, supposing jid contains a string that is also a key in data[0].
You can just do data[0][variableName] and this will return the data you want. for example. If data had a json string [{ "Name" : "Jane Doe"}] You could execute it like this.
var variableName = "Name";
console.log(data[0][variableName])
This would return "Jane Doe".
if you have your field names in an array you can loop through them using $.each or a for loop.
For example say your json string is [{"First_Name" : "Jane", "Last_Name" : "Doe", "Age" : 32}] you could get all the values from the json string doing this.
var FieldNames = ["First_Name" , "Last_Name", "Age"]
$.each(FieldNames, function(i,item) {
console.log(data[0][item])
}
OR
var FieldNames = ["First_Name" , "Last_Name", "Age"]
for(var i = 0; i < FieldNames.length; i++) {
console.log(data[0][FieldNames[i]])
}

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

Passing string array from ASP.NET to JavaScript

I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?
I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);
This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];

Categories

Resources