passing javascript attribute to javascript function - javascript

I am struggling to figure out how to pass a <div id> to another javascript. For example, at the start of my page I have the following script which creates a div id tag that allows me to dynamically select and change content of the page.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#stats').attr('src', '/hardware/' + subFolder + '/stats/usage.txt');
$('#hostInfo').attr('src', '/hardware/' + subFolder + '/stats/host.txt');
$('#folderContent').show();
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
This allows me to do the following - this creates a selector that a particular folder can be selected.
<div class="hidden-print">
<select id='folderList'></select>
</div>
When the folder list is selected above it allows me to change content like the items below:
like the above to another java script.
$(document).ready(function() {
$('#example3').DataTable( {
"processing": true,
"ajax": {
"url" : "../../reports/drives.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
} );
When i select a folder above from the selector i would like the folder under the URL under the AJAX to be modified along with it to update it.
UPDATE
After looking at this a bit further I don't think my explanation fit very well.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/server/' + subFolder + '/Logo/hardware.png');
$('#folderContent').show();
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
var thisId = $('folderList').attr('id');
I want to take this variable which should be a single folder and use it on a script like the one below.
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/server/' + subFolder + '/Logo/hardware.png');
I would like to take the "subfolder" and use it something like the following:
$(document).ready(function() {
$('#example3').DataTable( {
"processing": true,
"ajax": {
"url" : "/server/" + subfolder + "/Stats/Map.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
} );
I tried to get the method below to get a div id conversion and it doesn't have any data when i try it that way. I should have stated i want to use the variable in the sub folder in the script above... I tried a window.variable name i have tried the global variable and still nothing seems to be working correctly. My guess is that the way the variable is being processed is not carrying over.

You can access the id using $('#folderList').attr('id').
Assign that to a variable and pass it into your function. If you are loading a separate script using $(document).ready(), it may not be available unless it's a global variable.
Something like this might do the trick for you.
var thisId = $('#folderList').attr('id');
$(document).ready(function() {
$('#'+thisId).append('whatever');
} );

You can also pass it inside jQuery function using window.variable = value that will be considered as a global variable for that window object.

With your help i was able to diagnose and find the issue. When the variable is outside of the function it doesn't run. By adding it into the document.ready function it will keep the variable through changes of the dropdown. Then finding that because there are multiple initializations of the data-tables structure - i have to add the "destroy" flag = true. This destroys the old datatables and allows a new one to be created after you change the folder.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/hardware/' + subFolder + '/Logo/hardware.png');
$('#hdstats').attr('src', '/hardware/' + subFolder + '/hdstats/hdstats.csv');
$('#folderContent').show();
$('#example3').DataTable( {
"destroy": true,
"processing": true,
"ajax": {
"url" : "/hardware/" + subFolder + "/hdstats/stats.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});

Related

Multiple AJAX calls and show div on finish

I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});

How do I dynamically create a list in which each line has to have a certain format?

I need to dynamically create a list in JavaScript with a unique div id for each line. How do I do this?
HTML
The HTML code:
<ul class="sub-menu insert">
The ul class I am working with is "insert"
The JavaScript code has two functions:
The first JavaScript function
$(function() {
$.ajax({
type: 'GET',
url: 'json/data.json',
async: false,
beforeSend: function() {
},
dataType: 'json',
success: function(result) {
$(document).ready(function() {
var divsToAppend = "";
$.each(result, function(i) { //Item key
$("#insert").append += '<li id="' + i + '">"<div id="test_ID"' + i +'></div>" + '</li>');
});
});
}
});
Code snippet:
This is a String:
"<div id="test_ID" + i +></div>"
The first function one loops trough a JSON file, the intention is that it shall create a list, with as many lines as there is in the mentioned file. Each line in the list has to follow a certain syntax. And tt has to generate a unique div id for each line. The list connects with the ul class "insert" in the HTML code.
I want the generated list to look like this in HTML:
<li><div id="test_ID1"></div></li>
<li><div id="test_ID2"></div></li>
The unique div id that I mentioned:
"test_IDi"
The second JavaScript function
The second function connects with the unique "test_id" that is generated in the first function. It collects data from the JSON file. It works, but only when there is a single "div id". It has to be able to distinguish between the different unique "div id:s" that is generated by the first function.
$(function () {
$.ajax({
type: 'GET',
url: 'json/data.json',
async: false,
beforeSend: function () {/*loading*/
},
dataType: 'json',
success: function (result) {
$("#test_IDi").empty(); //Empty ID
$.each(result, function(i, v) {
$("#test_IDi").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>');
});
}
});
});
});
The JSON File (included for reference):
[
{"id": "a", "test": "Java", "testDate": "17-08-01"},
{"id": "b","test":"JavaScript","testDate": "17-08-02"}
]
How I wish that the finished list will look:
Java 17-08-01
JavaScript 17-08-02
Here you go.
Look at the below example:
var result = [{
data: ''
}, {
data: ''
}];
var jsonData = [{
"id": "a",
"test": "Java",
"testDate": "17-08-01"
}, {
"id": "b",
"test": "JavaScript",
"testDate": "17-08-02"
}];
$.each(result, function(index) {
$(".insert").append('<li><div id="test_ID' + index + '"></div></li>');
});
$.each(jsonData, function(index, value) {
$("#test_ID" + index).append('<li id="' + value.id + '">' + value.test + ' ' + value.testDate + '</li>');
});
$('#output-html').val($('#html-data').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="html-data">
<ul class="sub-menu insert">
</ul>
</div>
<div>
Output HTML:
<textarea id="output-html" rows="10" cols="55"></textarea>
</div>
I got a lot of valuable help from Gaurav to solve this. After I had worked a little more on the code I found a way to reduce it by removing "test_id", instead of adding the code from the second function directly to the loop that generates a new list element.
$(function() {
$.ajax({
type: 'GET',
url: 'json/data.json',
async: false,
beforeSend: function() {
},
dataType: 'json',
success: function(result) {
$(document).ready(function() {
$.each(result, function(i, v) {
$(".insert").append('<li>' + v.test + '</div></li>');
});
});
}
});
});

How to bind button function to a corresponding item in an array - AJAX, Firebase

I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}

How to reload a div with jquery

I am new to jQuery.
I have to reload a div after sending some values to server using ajax.
My jQuery code is
selectionChanged: function () {
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var columnname = record.columnname;
var datatype = record.datatype;
var columnlength = record.columnlength;
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
});
after this code is executed I want to reload a div
<div id="loadedtablecontainer"></div>
this div will get the selected data of 1st jtable .. and display it in this jtable.
So by using this div id I have to call or reload this div soon after above jQuery function got executed
Something like
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
$("#loadedtablecontainer");
So I am assuming the Ajax call returns the new content, so set the html() in the callback.
$.post('meta?action=dataload',
{
columnname : columnname,
datatype:datatype,
columnlength:columnlength
},
function (data) {
$( "#loadedtablecontainer" ).html(data);
}
);
You have a callback parameter which returns your result from post. Use that to manipulate the data and form the HTML. Then simply append it
$.post('meta?action=dataload', {
columnname : columnname, datatype:datatype,columnlength:columnlength
},
function (result) {
// make your manipulations here, (Ex: var manipulatedHTML )
$("#loadedtablecontainer" ).append(manipulatedHTML );
}
);
If its a json
function(result) {
//result is your json
var manipulatedHTML = '<div class="result">'+result.value"+'</div>';
}
$("#loadedtablecontainer" ).append(manipulatedHTML )
Use a for loop if its a json array
function loadCustomerCorpPopup(id) {
$("#eBody").mask("${loading}");
$.ajax({
url : '${url}/customer/ajax_customer_corporate_popup',
data : {
customerCorporateId : id,
},
dataType : 'text',
cache : false,
success : function(data) {
$('#popupId').html(data);
$('#popupId').modal('show');
$("#eBody").unmask("${loading}");
}
});
}
You can use this way $('#popupId').html(data);
data can a html code or url.

jQuery nested XML question

I am using jQuery to insert an HTML shell into a page, and populate the shell with XML. Here is the XML in question
<minorPropCategory title="Test Title 1">
<minorProp>FLV</minorProp>
<minorProp>BLV</minorProp>
<minorProp>RLV</minorProp>
</minorPropCategory>
<minorPropCategory title="Test Title 2">
<minorProp>LAS</minorProp>
<minorProp>ILV</minorProp>
<minorProp>BIL</minorProp>
</minorPropCategory>
So first, what I do is import an HTML snippet for each minorPropCategory, and add the title using this code
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
Then, what I want to do is add another HTML snippet, and then populate it. This is where I am having a problem. I can try it like this
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
But it never shows up on the page, because I don't think it is firing at the proper time. Alternatively, I tried moving the creation of the minor modules into the .load function of it's parent, but I run into another problem. The code looks like this.
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
$(this).find('minorProp').each(function(){
alert("minorPropFired");
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
alert("test");
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
The problem is, that the line with "$(this).find('minorProp').each(function(){" doesn't fire because "this" has changed. I guess, by now, my noob is showing. I feel like I am doing this in the wrong way. Any help would be appreciated. Thanks.
Posted below is the full .js file of what I am trying to do.
// JavaScript Document<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
//gets the code for the ad from the URL. Using URL jQuery add-on to make this super-easy
var adCode = $.url.param("adCode");
if (adCode != null){
//gets the ad code's XML file
$.ajax({
type: "GET", url: adCode+".xml", dataType: "xml",
success: function(xml) {
//Set the header image
$("#headerImg").attr(
{
src:$(xml).find('headerImage').text(),
alt:$(xml).find('headerImageAlt').text()
}
);
//set the header text
$("#headerText").html($(xml).find('adText').text());
//set the top image
$("#topImg").attr(
{
src:$(xml).find('topImage').text(),
alt:$(xml).find('topImageAlt').text()
}
);
//MAJOR MODULE CODE - This code reads all of the major modules, then adds a majorModule div, and populates it
//Gets all majorProps from ad XML
$(xml).find('majorProp').each(function(){
var propCode=$(this).text();
var majorModuleCode = "majorModule.html";
//names the div with a unique ID
div = $("<div id='"+propCode+"majorModule' class='majorModule'>");
//Sets loading message in case it takes longer than usual to load
div.html("Loading......");
//After majorModule.html code loads, starts populating module
div.load(majorModuleCode,"t",
function(){
//Get the XML for the prop, which contains prop specific stuff
$.ajax({
type: "GET",
url: propCode+".xml",
dataType: "xml",
success: function(xml2) {
$("#"+propCode+"majorModule").find(".propImg").attr(
{
src:$(xml2).find('smallImage').text(),
alt:$(xml2).find('smallImageAlt').text()
}
);
$("#"+propCode+"majorModule").find(".propLogoImg").attr(
{
src:$(xml2).find('smallLogo').text(),
alt:$(xml2).find('name').text()
}
);
$("#"+propCode+"majorModule").find(".viewCalendarLinkA").attr(
{
href:"https://www.harrahs.com/AvailabilityCalendar.do?propCode="+propCode+"&showHotDeal=Y"
}
);
$("#"+propCode+"majorModule").find(".learnMoreLinkA").attr(
{
href:$(xml2).find('homeLink').text()
}
);
$("#"+propCode+"majorModule").find(".propText").html(
$(xml2).find('bodyText').text()
);
}
});
//Get the lowest rate for the prop
$.ajax({
type: "GET",
url: "lowest_rate\\"+propCode+".xml",
dataType: "xml",
success: function(xml3) {
$("#"+propCode+"majorModule").find(".roomRate").html(
"$"+($(xml3).find('roomtype').filter(
function (index) {
return $(this).attr("lowest") == "Y";
}).text()).slice(0, -3)
)
}
});
}
);
$("#mainModuleContainer").append(div);
});
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
}
});
}
});
To fix this problem just before running minorDiv.load do something like this
var elem = $(this);
minorDiv.load(minorModuleContainerCode,"t", function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").
html(minorHeader);
// replace $(this) with elem here
elem.find('minorProp').each(function(){
...
}
...
}
This will keep the reference to correct object in your nested functions.

Categories