How to access content in an object literal? - javascript

Can someone tell me what the best way is to store content in an object literal and how to access it using my JS pattern? I can't seem to get it to work.
Namespace.object = {
var data = [{"myid1" : "<p>My content 1</p>"}];
method: function () {
var myData = Namespace.object.data[0].id;
}
};

To store:
Namespace.object = {
data: [{"myid1" : "<p>My content 1</p>"}],
method: function () {
var myData = Namespace.object.data[0].id;
}
};
To access:
var theFirstData = Namespace.object.data[0];
var myId1 = Namespace.object.data[0].myid1;
// Alternatively...
var myId1b = Namespace.object.data[0]['myid1'];
Namespace.object.method();

Related

JSON data to Array

This is my Javascript function that gets data from the HTML form.
$(function postProduct() {
$('#btn').click(function() {
var productName = document.getElementById("name").value;
var productDetail = document.getElementById("detail").value;
var productCategory = document.getElementById("category").value;
var dimensions = [productName, productDetail, productCategory];
var keys = $.map(dimensions, function(value, key) {
return value;
});
$.ajax({
type: "POST",
url: "api/product/addproduct",
data: keys,
success: function(result) {
alert('successful : ' + result);
return result;
},
error: function(error) {
alert("Not Working..");
}
});
}
});
});
This is my controller:
[HttpPost]
[Route("api/product/addproduct")]
public IActionResult AddProduct([FromBody] string[] addproduct)
{
var pProductName= addproduct[0];
var pProductDetail= addproduct[1];
var pProductCategory= addproduct[2];
Hotel NewProduct = new Product();
{
NewProduct.ProductName= pProductName;
NewProduct.ProductDetail= pProductDetail;
NewProduct.ProductCategory= pProductCategory;
}
_db.Products.Add(NewProduct);
_db.SaveChanges();
//create a new route for post method by id
return CreatedAtRoute(new { id = addproduct}, addproduct);
}
So, I'm trying to pass the inputted form and pass it to the controller by AJAX, However, it just fails.
This is the function that I use to make the json data to an array:
var dimensions = [productName, productDetail, productCategory];
var keys = $.map(dimensions, function(value, key) {
return value;
});
Or should I recode my controller for accepting json data. If so, please give me an example on doing it. Sorry, I'm new at web api.
UPDATE:
This is my jsondata:
productName: name
productDeatil: detail
productCategory:category
This is my Array:
keys:(7) ["name", "detail", "category"]
In your Ajax request, assign the data key to the following value...
{ productName: document.getElementById("name").value, productDetail: document.getElementById("detail").value, productCategory: document.getElementById("category").value }
This is a typical JSON formatted object.
You could then also remove your variable assignments and map function.
Finally you'd need to look into how to process this formatted JSON in your controller.
I'm unsure of how to go about this in asp.net-core-mvc but it could be something as simple as changing
var pProductName= addproduct[0];
to
var pProductName= addproduct.productName
Is the spacing between NewProduct and properties such as .ProductName intentional?
NewProduct .ProductName = pProductName;
Shouldn't it be like this?
Hotel NewProduct = new Product();
NewProduct.ProductName = pProductName;
NewProduct.ProductDetail = pProductDetail;
NewProduct.ProductCategory = pProductCategory;
With simplified object creation:
Hotel NewProduct = new Product() {
ProductName= pProductName,
ProductDetail= pProductDetail,
ProductCategory= pProductCategory
};
add data: JSON.stringifly(keys) in ajax solve the problem. Thank you for everyone's help!

AJAX values from database to html skipped

I have these employee information which display if you click on the employee box. But sometimes the value of some fields returns null even if they have a value but when I retry it will return ok. Is this some code problem? here is my code...
First I store the elements into an object
var uamnumber = $(this).find(".box-list-agents-uamnumber").text();
var agentInfo = $(this).find(".box-list-agents-info").text().split("/");
var agentElement = {
txtUam: $("#search-txt-uam-number"),
txtFirstName: $("#search-txt-first-name"),
txtMiddleName: $("#search-txt-middle-name"),
txtLastName: $("#search-txt-last-name"),
txtContactNumber: $("#search-txt-contact-number"),
txtEmailAddress: $("#search-txt-email-address"),
txtClassification: $("#search-txt-classification"),
txtAgentStatus: $("#search-txt-agent-status"),
txtReasonResignation: $("#search-txt-reason-resignation"),
txtCsp: $("#search-txt-csp-name"),
txtProgramId: $("#search-txt-program-name"),
txtSite: $("#search-txt-site-name"),
txtBirthDate: $("#search-txt-birth-date"),
txtLiveDate: $("#search-txt-live-date"),
txtEndDate: $("#search-txt-end-date"),
txtProgram: $("#search-program-name")
};
var agentParam = {
uam: uamnumber,
csp: agentInfo[0],
program: agentInfo[1]
}
Dashboard_GetAgentInfo(agentParam, agentElement);
$("#search-well-tool-access").hide();
$("#search-well-agent-info").fadeIn();
and here is the function that has been called.
function Dashboard_GetAgentInfo(agentInfo,agentElement) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Dashboard_GetAgentInfo",
data: JSON.stringify(agentInfo),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var uamdetails = response.d;
var appendItem = "";
$.each(uamdetails, function (index, Dashboard_GetAgentInfoInfo) {
var uamnumber = Dashboard_GetAgentInfoInfo.uamnumber;
var firstname = Dashboard_GetAgentInfoInfo.firstname;
var middlename = Dashboard_GetAgentInfoInfo.middlename;
var lastname = Dashboard_GetAgentInfoInfo.lastname;
var contactnumber = Dashboard_GetAgentInfoInfo.contactnumber;
var emailaddress = Dashboard_GetAgentInfoInfo.emailaddress;
var csp = Dashboard_GetAgentInfoInfo.csp;
var cspid = Dashboard_GetAgentInfoInfo.cspid;
var program = Dashboard_GetAgentInfoInfo.program;
var programid = Dashboard_GetAgentInfoInfo.programid;
var site = Dashboard_GetAgentInfoInfo.site;
var siteid = Dashboard_GetAgentInfoInfo.siteid;
var birthdate = Dashboard_GetAgentInfoInfo.birthdate;
var livedate = Dashboard_GetAgentInfoInfo.livedate;
var enddate = Dashboard_GetAgentInfoInfo.enddate;
var classification = Dashboard_GetAgentInfoInfo.classification;
var agentStatus = Dashboard_GetAgentInfoInfo.agentstatus;
var reasonResignation = Dashboard_GetAgentInfoInfo.reasonresignation;
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
$(agentElement.txtMiddleName).val(middlename);
$(agentElement.txtLastName).val(lastname);
$(agentElement.txtContactNumber).val(contactnumber);
$(agentElement.txtEmailAddress).val(emailaddress);
$(agentElement.txtClassification).val(classification);
$(agentElement.txtAgentStatus).val(agentStatus);
$(agentElement.txtReasonResignation).val(reasonResignation);
$(agentElement.txtCsp).val(cspid)
$(agentElement.txtProgramId).val(programid);
$(agentElement.txtSite).val(siteid);
$(agentElement.txtBirthDate).val(birthdate);
$(agentElement.txtLiveDate).val(livedate);
$(agentElement.txtEndDate).val(enddate);
$(agentElement.txtProgram).text(program);
NumbersOnly();
});
},
error: function (XMLhttpRequest) {
alert("error in Dashboard_GetAgentInfo");
console.log(XMLhttpRequest);
}
});
}
and this is the web service that has been called
public List<Dashboard_GetAgentInfoDetails> Dashboard_GetAgentInfo(string uam, int csp, int program) /*int CSP, int Program*/
{
DataTable table = null;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[Dashboard_GetAgentInfo]";
cmd.Parameters.AddWithValue("#uam", uam);
cmd.Parameters.AddWithValue("#csp", csp);
cmd.Parameters.AddWithValue("#program", program);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
table = this.dbConn.ExecuteDataTable(cmd);
Dashboard_GetAgentInfo_Details.Clear();
foreach (DataRow row in table.Rows)
{
Dashboard_GetAgentInfoDetails _list = new Dashboard_GetAgentInfoDetails();
_list.uamnumber = row["UAM #"].ToString();
_list.firstname = row["First Name"].ToString();
_list.middlename = row["Middle Name"].ToString();
_list.lastname = row["Last Name"].ToString();
_list.contactnumber = row["Contact Number"].ToString();
_list.emailaddress = row["Email Address"].ToString();
_list.csp = row["CSP"].ToString();
_list.cspid = Convert.ToInt32(row["CSPID"].ToString());
_list.program = row["Program"].ToString();
_list.programid = Convert.ToInt32(row["ProgramID"].ToString());
_list.site = row["Site"].ToString();
_list.siteid = Convert.ToInt32(row["SiteID"].ToString());
_list.birthdate = row["BirthDate"].ToString();
_list.livedate = row["LiveDate"].ToString();
_list.enddate = row["EndDate"].ToString();
_list.classification = Convert.ToInt32(row["Classification"].ToString());
_list.agentstatus = row["Agent Status"].ToString();
_list.reasonresignation = row["Reason Resignation"].ToString();
Dashboard_GetAgentInfo_Details.Add(_list);
}
return Dashboard_GetAgentInfo_Details;
}
does storing elements into an object and passing it as a parameter is a good practice of coding? and what may be the cause of the select having no value even if I when I try to console.log the value and it returns ok?
I think the problem is here:
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
...
You should do:
agentElement.txtUam.val(uamnumber);
agentElement.txtFirstName.val(firstname);
...
There is no need to use jquery selector $, because agentElement.txtUam is already one, also gathering elements inside an object is a best practice because you can't pass each one as a parameter.
The perfect answer to this is add a call back function so the dropbox have a option first before adding the val. Here is the idea of adding a callback function
function Filtering_GetSite(siteElement, callback) {
if (typeof (callBack) == "function") {
callBack();
}
}
the line checking of the callback parameter is to ensure that it its a function before executing so you can call the function like this Filtering_GetSite(sample) insted of Filtering_GetSite(sample,function(){}) when omiting the callback function

Class method in javascript is not a function

The answer must be obvious but I don't see it
here is my javascript class :
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923",
isComponentAvailable = function() {
var alea = 100000*(Math.random());
$.ajax({
url: Authentification.ACCESS_MASTER + "/testcomposant?" + alea,
type: "POST",
success: function(data) {
echo(data);
},
error: function(message, status, errorThrown) {
alert(status);
alert(errorThrown);
}
});
return true;
};
};
then I instanciate
var auth = new Authentification();
alert(Authentification.ACCESS_MASTER);
alert(auth.componentAvailable);
alert(auth.isComponentAvailable());
I can reach everything but the last method, it says in firebug :
auth.isComponentAvailable is not a function
.. but it is..
isComponentAvailable isn't attached to (ie is not a property of) your object, it is just enclosed by your function; which makes it private.
You could prefix it with this to make it pulbic
this.isComponentAvailable = function() {
isComponentAvailable is actually attached to the window object.
isComponentAvailable is a private function. You need to make it public by adding it to this like so:
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923";
this.isComponentAvailable = function() {
...
};
};
Another way to look at it is:
var Authentification = function() {
// class data
// ...
};
Authentification.prototype = { // json object containing methods
isComponentAvailable: function(){
// returns a value
}
};
var auth = new Authentification();
alert(auth.isComponentAvailable());

Accessing Data from JavaScript Object's Array Member Variable

I'm writing a jQuery plugin for work which pulls in RSS feed data using Google's Feed API. Using this API, I'm saving all of the relevant RSS feed data into an object, then manipulating it through methods. I have a function which is supposed to render the RSS feed onto the webpage. Unfortunately, when I try to display the individual RSS feed entries, I get an error. Here's my relevant code:
var RSSFeed = function(feedTitle, feedUrl, options) {
/*
* An object to encapsulate a Google Feed API request.
*/
// Variables
this.description = "";
this.entries = [];
this.feedUrl = feedUrl;
this.link = "";
this.title = feedTitle;
this.options = $.extend({
ssl : true,
limit : 4,
key : null,
feedTemplate : '<article class="rss-feed"><h2>{title}</h1><ul>{entries}</ul></article>',
entryTemplate : '<li><h3>{title}</h3><p>by: {author} # {publishedDate}</p><p>{contentSnippet}</p></li>',
outputMode : "json"
}, options || {});
this.sendFeedRequest = function() {
/*
* Makes the AJAX call to the provided requestUrl
*/
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
// Save the data in a temporary object
var responseDataFeed = data.responseData.feed;
// Now load the data into the RSSFeed object
self.description = responseDataFeed.description;
self.link = responseDataFeed.link;
self.entries = responseDataFeed.entries;
});
};
this.display = function(jQuerySelector) {
/*
* Displays the RSSFeed onto the webpage
* Each RSSEntry will be displayed wrapped in the RSSFeed's template HTML
* The template markup can be specified in the options
*/
var self = this;
console.log(self);
console.log(self.entries);
};
};
$.rssObj = function(newTitle, newUrl, options) {
return new RSSFeed(newTitle, newUrl, options);
};
// Code to call the jquery plugin, would normally be found in an index.html file
rss = $.rssObj("Gizmodo", "http://feeds.gawker.com/Gizmodo/full");
rss.sendFeedRequest();
rss.display($('div#feed'));
Obviously, my display() function isn't complete yet, but it serves as a good example. The first console.log() will write all of the relevant data to the console, including the entries array. However, when I try to log the entries array by itself, it's returning an empty array. Any idea why that is?
I guess the problem is that display() is called without waiting for the AJAX request to complete. So the request is still running while you already try to access entries - hence the empty array.
In order to solve this you could move the call to display() into the callback of $.getJSON(). You just have to add the required selector as a parameter:
this.sendFeedRequest = function(selector) {
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
var responseDataFeed = data.responseData.feed;
...
self.entries = responseDataFeed.entries;
self.display(selector);
});
};
EDIT:
If you don't want to move display() into the callback, you could try something like this (untested!):
var RSSFeed = function(feedTitle, feedUrl, options) {
...
this.loading = false;
this.selector = null;
this.sendFeedRequest = function() {
var self = this;
self.loading = true;
$.getJSON(this.encodeRequest(), function(data) {
...
self.loading = false;
if (self.selector != null) {
self.display(self.selector);
}
});
};
this.display = function(jQuerySelector) {
var self = this;
if (self.loading) {
self.selector = jQuerySelector;
}
else {
...
}
};
};

pass variable into javascript object

Can you please help with my problem
I have the following JavaScript object:
var data = {
'rows[0][name]': 'foshka',
'rows[0][tel]': '096',
'rows[0][opt]': 'none'
};
The problem is that i get an error while trying to pass variable as rows index:
var i = 0;
var data = {
'rows['+ i +'][name]': 'one',
'rows['+ i +'][tel]': '096',
'rows['+ i +'][opt]': 'none'
};
Thanks in advance
Your code has to be
var data = {};
data[ 'rows['+ i +'][name]' ] = 'one';
data[ 'rows['+ i +'][tel]' ] = '069';
However you might want to change your structure to sth like this:
var data ={};
var i = 0;
data['rows'][i]['name'] = 'one';
Or even cleaner:
var data = { rows[] };
var i = 0;
data['rows'][i] = { 'name' : 'one', 'tel' : 069' };
// so you can access them like this:
alert ( data['rows'][i]['name'] );
I think your data should look like this:
var data = {
rows: [{
name: 'one',
tel: '096',
opt: null
}]
};
That way you can simply add new rows if needed.

Categories

Resources