How can I dynamically create unique objects within .each()? - javascript

I'm running a .each() on a list of items and categorizing those items in my HTML. In a function after that I'm checking which of those items is checked (checkboxes). In my function (prepareTrainings();) that finds which boxes were checked, I need it to display data from the result of the .each(). Basically, if the user checked X checkbox, show the Course Name and URL for that item...
My question: I'm not sure what would be best practice. Should I be creating an object to store those values inside my if(trainingGroup etc.) statements?
$.ajax({
url: "mySite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
var dynCourseId = courseName.replace(/\s+/g, '')
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+dynCourseId+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+dynCourseId+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
function prepareTrainings() {
var idSelector = function() {
return this.id;
};
var checkedCourses = $(":checkbox:checked").map(idSelector).get();
alert("IDs for Courses Selected: " + checkedCourses);
}

Keeping your processed objects in a global var makes sense. Define e.g. an object like so:
var courses = {};
Then in your .each function, extract the information from your HTML elements like you already do and store each result in another object:
$.each(data.d.results, function(index) {
var $this = $(this);
var course = {}; //Create empty object
course.name = $this.attr('Title');
course.number = $this.attr('Course_x0020_Number');
course.url = $this.attr('URL');
course.trainingGroup = $this.attr('Training_x0020_Group');
course.recurrence = $this.attr('Recurrence');
course.id = course.name.replace(/\s+/g, '')
//Store your course by id in the courses object
courses[course.id] = course;
//...
Later when checking which checkboxes are checked, you can retrieve the information of each course like so:
var checkedIDs = $(":checkbox:checked").map(idSelector).get();
var course = courses[checkedIDs[0]]; //fetches the first selected course
//Now you can do whatever with the data, like print lists...
(...).innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+course.id+'"/>'+course.name+course.recurrence+'</li></ul>';
I hope I understood your question correctly, if not leave a comment.

Related

Loop in IndexedDB Transactions

I am using the product design tool "Lumise" which saves the guest designs and uploads in IndexedDB. I want to save the data which is saved in these object stores in MySQL table using the insert query. I have created a selectindexeddb.js file and indexeddbtomysql.php file and already there is a file for the tool which created the IndexedDB and updating it called "app-uncompressed.js".
my question is: I want to make the loop for each transaction happen to the design from creating, update or delete how can I do it from separate js file.
hint: I have tried to write this for loop in lumise js file but it shows bunch of errors also because this file is extremely huge.
any help ?
app-uncompressed.js :)
https://pastebin.com/cm6aNZ2A
Another Hint:)
in this file, you can focus in 12177 lines which starts creating IndexedDB
selectindexeddb.js
var db;
var request = indexedDB.open("lumise");
var transaction = db.transaction(["designs"]);
var objectStore = transaction.objectStore("designs");
var request = objectStore.get("K730MRT0"); // this i want it to have it from app_uncompressed.js as a variable.
// i want to make the loop here ?!
request.onsuccess = function(event) {
// Do something with the request.result!
var designid = request.result.id;
var designname = request.result.name;
var designscreenshot = request.result.screenshot;
console.log("rsults is " + designid);
$.ajax({
url: 'indexeddbtomysql.php',
method: 'POST',
data: {design_id:designid ,design_name:designname,design_screenshot:designscreenshot },
success: function(data) {
alert("saved y marweta ;)")
}
});
};
indexeddbtomysql.php
<?php
session_start();
include '../config.php';
$design_id = $_POST['design_id'];
$design_name = $_POST['design_name'];
$design_screenshot = $_POST['design_screenshot'];
$query = 'INSERT INTO `user_designs`( `key`, `name`, `screnshot`) VALUES ($design_id
,$design_name , $design_screenshot);';
?>
updated I have tried to put the for loop in the app_uncompersed.js but it didn`t work
save : function(ob, storeName, callback) {
if (this.db == null)
return callback(null);
var i ;
for (i = 0; i < count(rows); i++) {
var trans = this.db.transaction(ob.length === 2 ?
[storeName, 'dumb'] : [storeName], "readwrite");
var store = trans.objectStore(storeName);
if (ob.id === null || ob.id === undefined)
ob.id = parseInt(newDate().getTime()/1000)
.toString(36)+':'+Math.random().toString(36).substr(
2);
var obj = $.extend({
created: new Date().getTime()
}, (ob[0] !== undefined ? ob[0] : ob));
var process = store.put(obj, obj.id);
if (typeof callback == 'function')
process.onsuccess = callback;
console.log("ABC");
if (ob[1] !== undefined) {
var obj_dumb = $.extend({
id: obj.id,
created: obj.created
}, ob[1]);
trans.objectStore('dumb').put(obj_dumb, obj.id);
}
var designid = obj.id; //this var i want to save
}
},
I am currently learning IndexedDB and find this link to be very useful. There is a tutorial in it which covers what you're trying to achieve.
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

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

Passing multiple form data to PHP controller

$('#save').on("click", function() {
//collect the form data while iterating over the inputs
var data = [];
$('[name=form]').find('input, select, textarea').each(function() {
if ($(this).attr('value') != '') {
var name = $(this).attr('name');
var value = $(this).attr('value');
data[name] = value;
}
})
for (var i = 1, ii = form.length; i < ii; i++) {
var name = 'form' + i;
$('[name=' + name + ']').find('input, textarea').each(function() {
data[i] = [];
if ($(this).attr('value') != '') {
var name = $(this).attr('name');
var value = $(this).attr('value');
data[i][name] = value;
}
})
}
$.post('foo', data,
function(data) {
console.log(data);
I have the above jquery code where I wish to post multiple form data into my PHP backend controller.
In my controller, I used
$input = Input::all()
Question 1
How do I access the data in the array that I have passed?
Let's say I have foo input and bar input in my form. I tried to use
$input['foo']
$input['bar']
but I'm getting internal server error with undefined index error.
Question 2
How do I access the data of the data[i][name]? Let's say I have form1, form2, form3, so it my data array will become
$data[1][foo]
$data[2][foo]
$data[3][foo]
How can I access these in my PHP controller?
Thanks and sorry for the long question
with FormData object.
var formdata = new FormData();
formdata.append("name", value);
on server-side you read values like this:
$name = $_POST["name"];

Cookie is overwriiting issue

I have following code I use Jquery cookie plugin to set cookie.I need to store multiple values to a a cookie variable using jquery but every time its overwrite so multiple value doesn't store.please have a look into my code and help me.I have a select box and its name is inserted into a cookie variable every time.
$(".cookieul").on("click",function(){
var a ='';
var myCookies = [];
var newValue = $(".client option:selected").text();
a += newValue;
myCookies.push(a);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
});
You may write like this -
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();// your new selected text
var old_value_json = $.cookie("example"); // check your plugin get cookie syntax
var old_value_arr = [];
old_value_arr = $.parseJSON(old_value_json); //converting your stored JSON string to javascript array
old_value_arr.push(newValue ); // pushing new value to array
$.cookie("example", JSON.stringify(old_value_arr ), { expires: 7 });//setting new value to cookie
});
This solves the issue.Any other better way
var myCookies = [];
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();
var old_value_json = $.cookie("example");
myCookies = $.parseJSON(old_value_json)
myCookies.push(newValue);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
var storedAry = JSON.parse($.cookie('example'));
console.log(unique(storedAry));
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
});

Use a FOR loop within an AJAX call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:
I never used the for loop in JS, but seems familiar anyway.
The way the loop is made, obviously wont work:
for (i=0;i<required.length;i++) {
var required[i] = $('#'+required[i]).attr('value');
This will create the variables i want, how to use them?
HOPEFULLY, you guys can help me!!! Thank you very much!
required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];
function ajaxrequest() {
for (i = 0; i < required.length; i++) {
var required[i] = $('#' + required[i]).attr('value');
var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: dataString,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.
jQuery:
required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];
function ajaxrequest() {
var params = {}; // initialize object
//loop through input array
for (var i=0; i < required.length; i++) {
// set the key/property (input element) for your object
var ele = required[i];
// add the property to the object and set the value
params[ele] = $('#' + ele).val();
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: params,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}
Demo: http://jsfiddle.net/kPR69/
What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;
var obj = {};
$('.save').each(function () {
var key = $(this).attr('id');
var val = $(this).val();
if (typeof (val) == "undefined")
val = "''"
obj[key] = val;
}
Then send obj as the data property of your AJAX call....
There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.
I would suggest using pre-written library, a few I included below.
http://jquery.malsup.com/form/#validation
https://github.com/posabsolute/jQuery-Validation-Engine
Otherwise the follow would get you close. You may need to covert the array into a string.
var required = ['nome','sobrenome'];
function ajaxrequest() {
var values;
for (i = 0; i < required.length; i++) {
var values[i] = $('#' + required[i]).attr('value');
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: values,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}

Categories

Resources