i got this code
function get_players()
{
$.ajax({
type: "POST",
url: "get_players.php",
dataType: "html",
success: function(data) {
var str = data;
var chars = str.split("<br />");
for(var i = chars.length - 1; i >= 0 ;i-- ) {
chars[i] = chars[i].split('/');
var o = document.getElementById(chars[i][0]);
var aimt = i;
if (!o) {
if (aimt!=chars.length -1) {
$('#gracze').html('<div id="'+chars[aimt][0]+'" class="char"><div id="char_name" style="left:-'+(((chars[aimt][3].length*9)/2)-16)+'px;width:'+(chars[aimt][3].length*9)+'px;">'+chars[aimt][3]+'</div></div>'+$('#gracze').html());
$('#'+chars[aimt][0]).css("top", chars[aimt][2]*32-16+"px");
$('#'+chars[aimt][0]).css("left", chars[aimt][1]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]+1);
}
} else {
$('#'+chars[aimt][0]).animate({
"top": chars[aimt][2]*32-16+"px", "left": chars[aimt][1]*32+"px"
}, { duration: 300});
//$('#'+chars[aimt][0]).css("top", chars[aimt][1]*32-16+"px");
//$('#'+chars[aimt][0]).css("left", chars[aimt][2]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]);
}
}
}});
setTimeout("get_players();", 300);
}
which receives players from this
5/7/13/GodFather
6/7/10/dsfsf
7/8/13/fdsf
and i want to ask how to delete div if there's no info about user
As you don't know which div elements to remove, the only way is removing them all then adding those you get from the AJAX response.
To remove them all, use the class that you already have:
$(".char").remove();
Add this line to the success function, before iterating over the lines.
OK, you can save the ID values returned by the AJAX call in array then remove any that does not exist in the array. Revised function code:
success: function(data) {
var str = data;
var chars = str.split("<br />");
var arrDivIDs = new Array();
for(var i = chars.length - 1; i >= 0 ;i-- ) {
chars[i] = chars[i].split('/');
arrDivIDs[chars[i][0]] = true;
var o = document.getElementById(chars[i][0]);
var aimt = i;
if (!o) {
if (aimt!=chars.length -1) {
$('#gracze').html('<div id="'+chars[aimt][0]+'" class="char"><div id="char_name" style="left:-'+(((chars[aimt][3].length*9)/2)-16)+'px;width:'+(chars[aimt][3].length*9)+'px;">'+chars[aimt][3]+'</div></div>'+$('#gracze').html());
$('#'+chars[aimt][0]).css("top", chars[aimt][2]*32-16+"px");
$('#'+chars[aimt][0]).css("left", chars[aimt][1]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]+1);
}
} else {
$('#'+chars[aimt][0]).animate({
"top": chars[aimt][2]*32-16+"px", "left": chars[aimt][1]*32+"px"
}, { duration: 300});
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]);
}
}
$(".char").each(function(index) {
if (!arrDivIDs[$(this).attr("id")])
$(this).remove();
});
}
Use .remove() http://api.jquery.com/remove/
EDIT
Where you have the check to see whether there is any data coming back (assume var o) you can do this:
o.remove();
EDIT 2
You can use variables in jQuery to select the id:
$("#" + chars[i][0]).remove();
Related
Did anyone know how i can send all this stuff with ajax to a search.php? it is already working but only with a search bar. I want to add to the search bar these variables. Its only important for the sort variable(the div with the sort id) to send the data on the beginning.
i think it would work to save the var into divs and get the values with document.getElementById('').getAttribute('value') but i still need to find out how to add this line of code to this ajax and that the ajax constantly check for changes in this divs. i still want that the ajax file send a output before i even touched the searchbar and the divs
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"post",
data:{search:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
function gettagValue() {
var checks = document.getElementsByClassName('tag');
var strtag = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
str += checks[i].value + "#";
}
}
alert(strtag);
}
function getblacklistValue() {
var checks = document.getElementsByClassName('blacklist');
var strblacklist = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
strblacklist += checks[i].value + "#";
}
}
alert(strblacklist);
}
function getbrandValue() {
var checks = document.getElementsByClassName('brand');
var strbrand = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
strbrand += checks[i].value + "#";
}
}
alert(strbrand);
}
alert(document.getElementById('sort').getAttribute('value'));
Do you mean that you want to send the values you're currently alerting? For starters, return those values instead of just alerting them:
function gettagValue() {
// ...
return strtag;
}
// same for the getblacklistValue and getbrandValue functions
Then in your AJAX code, call those functions to get those values and include them in the data:
function load_data(query)
{
let tagValue = gettagValue();
let blacklistValue = getblacklistValue();
let brandValue = getbrandValue();
$.ajax({
url:"search.php",
method:"post",
data:{
search:query,
tagValue:tagValue,
blacklistValue:blacklistValue,
brandValue:brandValue
},
success:function(data)
{
$('#result').html(data);
}
});
}
I'm using a for loop to search api results and build an array of objects so I can use that data and append it to the DOM. I'm doing this because Flickr's API's results aren't consistent to their values. For example, I'm looking for "aperture" and sometimes it's index number is [9], sometimes it's [11], and so on. I'm not sure if there's another way to achieve the results I'm looking for. I figured I could just loop through the results and search for the values I need.
Is there a way to grab only the last instance of the array? As it is now if I were to call exifArray[9].aperture it would show the result multiple times and also as undefined when the loop hasn't reached that part yet. I attempted to move the console.log(exifArray) to just outside of the for loop so it wouldn't repeat but it just returns the empty array that was declared at the top of the function.
Here's a screen shot of the console and also a code snippet:
Flickr.prototype.exifData = function(results) {
var apiKey = '';
var self = this;
var exifArray = [];
for (var i=0; i<results.photos.photo.length; i++) {
var currentId = results.photos.photo[i].id;
var exifData = $.ajax({
url: "https://api.flickr.com/services/rest/?method=flickr.photos.getExif&api_key=" + apiKey + "&photo_id=" + currentId + "&format=json",
dataType: "jsonp",
jsonp: 'jsoncallback',
type: "GET",
})
.done(function(exifResults) {
var options = {};
if (exifResults.stat === "ok") {
for (var x=0; x<exifResults.photo.exif.length; x++) {
var labelArray = exifResults.photo.exif[x].label;
if (labelArray === 'Model') {
options.cameraType = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Lens Model') {
options.lensModel = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Exposure') {
options.exposure = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Aperture') {
options.aperture = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'ISO Speed') {
options.iso = exifResults.photo.exif[x].raw._content;
} else {continue}
}
}
exifArray.push(options);
console.log(exifArray);
if (exifResults.stat === "ok") {
self.content.renderExifData(exifArray);
}
})
}
}
You can use pop()
var lastItem = arr.pop();
I'm trying to make an XML based menu with JavaScript, XML and jQuery. I've been successful at getting the categories of the menu, but haven't been able to generate the items in the categories.
My script is as follows, and later in this thread, I've asked for suggestions for this code:
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function() {
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse) {
var data = $("item", xmlResponse).map(function() {
return {
id: $("animal_id", this).text(),
title: $("animal_title", this).text(),
url: $("animal_url", this).text(),
category: $("animal_category", this).text().split('/'),
};
}).get();
var first_item = category_gen(data, 0);
$('ul.w-nav-list.level_2').append(first_item);
var categnumber = new Array();
for (i = 1; i <= data.length; i++) //for splitting id, and getting 0 for category_number (1 or 2 or 3...and so on)
{
categnumber[i] = data[i].id.split('_');
console.log(categnumber[i][0]);
for (j = 1; j <= data.length; j++) //appending via a function.
{
var data_text = category_or_animal(data, categnumber, j);
console.log(data_text);
$('ul.w-nav-list.level_2').append(data_text);
}
}
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return '</ul>' + animal_gen(d, k);
}
function category_gen(d, z) {
var category_var = '<li class="w-nav-item level_2 has_sublevel"><a class="w-nav-anchor level_2" href="javascript:void(0);"><span class="w-nav-title">' + d[z].category + '</span><span class="w-nav-arrow"></span></a><ul class="w-nav-list level_3">';
return category_var;
}
function animal_gen(d, z) {
var animal_var = '<li class="w-nav-item level_3"><a class="w-nav-anchor level_3" href="animals/' + d[z].url + '"><span class="w-nav-title">' + d[z].title + '</span><span class="w-nav-arrow"></span></a></li>';
return animal_var;
}
}, error: function() {
console.log('Error: Animals info xml could not be loaded.');
}
});
});
Here's the JSFiddle link for the above code: http://jsfiddle.net/mohitk117/d7XmQ/4/
In the above code I need some alterations, with which I think the code might work, so I'm asking for suggestions:
Here's the function that's calling separate functions with arguments to generate the menu in above code:
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return animal_gen(d, k) + '</ul>';
}
At the if(catg1[0] != catg2[0]) it checks if the split string 1_2 or 1_3 is equal to 1_1 or 1_2 respectively. By split, I mean the first element: 1 .... if you have a look at the xml: [ :: Animals XML :: ], you'll see that the animal_id is in the format of %category_number% _ %item_number% ... So I need to create the menu with CATEGORY > ITEM (item=animal name)
Now if I could return category_gen() + animal() with animal(){ in a for loop for all the matching category id numbers} then maybe this could be complete! But I don't of a count script for conditioning the for loop (i=0;i<=count();i++)...
Would anyone know of how to get this script functioning?
Hard to tell what the provided JSFiddle is trying to do.
This is my best stab at it. I used JQuery to parse the XML out into categories and generate lists of items.
http://jsfiddle.net/d7XmQ/8/
"use strict";
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function () {
var $menu = $('#menu');
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: handleResponse,
error: function () {
console.log('Error: Animals info xml could not be loaded.');
}
});
function handleResponse(xmlResponse) {
var $data = parseResponse(xmlResponse);
createMenu($data);
}
function parseResponse(xmlResponse) {
return $("item", xmlResponse).map(function () {
var $this = $(this);
return {
id: $this.find("animal_id").text(),
title: $this.find("animal_title").text(),
url: $this.find("animal_url").text(),
category: $this.find("animal_category").text()
};
});
}
function createMenu($data) {
var categories = {};
$data.each(function (i, dataItem) {
if (typeof categories[dataItem.category] === 'undefined') {
categories[dataItem.category] = [];
}
categories[dataItem.category].push(dataItem);
});
$.each(categories, function (category, categoryItems) {
var categoryItems = categories[category];
$menu.append($('<h2>').text(category));
$menu.append(createList(categoryItems));
});
}
function createList(categoryItems) {
var $list = $('<ul>');
$.each(categoryItems, function (i, dataItem) {
$list.append(createItem(dataItem));
});
return $list;
}
function createItem(dataItem) {
return $('<li>').text(dataItem.title);
}
});
You can solve this without using any for/while loop or forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
Using this code I am inserting the code into listbox.
<select id="lstCodelist" size="17" name="lstCodelist" style="width:100%;height:280px;background-color:#EFEFFB;"></select>
Using this code I am displaying data in to lstCodelist box.
$.fn.fillSelectDD = function (data) {
return this.clearSelectDD().each(function () {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function (index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}
});
}
});
}
This is the function I am calling to insert into one list box to other list.
function DoInsert(ind) {
var sourceIndex = $("#lstAvailableCode").val();
var targetIndex = $("#lstCodelist").val();
var success = 0;
var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
var functionName = "/Ajax/SaveCodeforInsert";
if (ind == "plan") {
functionName = "/Ajax/SaveCodeforInsertForPlan";
}
$.ajax({
type: "POST",
traditional: true,
url: functionName,
async: false,
data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
dataType: "json",
error: function (data) {
alert("Error Adding Code");
FinishAjaxLoading();
},
success: function (data) {
if (data == 0) { success = 1; } else { success = data; }
// $("#lstCodelist option").eq(1).attr('selected', 'selected')
$("#lstCodelist option:first-child").attr("selected", "selected");
FinishAjaxLoading();
}
});
but using this code in my success function I am not able to select assign or hightlight or select to this lstCodelist box.
// $("#lstCodelist option").eq(1).attr('selected', 'selected')
$("#lstCodelist option:first-child").attr("selected", "selected");
but its not working in my code right now is that I am doing something wrong here?
Thanks
I think in selects, just use $("#select_id").val(default_val); to select the value you need.
http://api.jquery.com/val/
[UPDATE]
Thanks guys,final code:
var EUR_share_cost = 0;
var USD_share_cost = 0;
var GBP_share_cost = 0;
var EUR_total_cost = 0;
var USD_total_cost = 0;
var GBP_total_cost = 0;
$.ajax({
url: '/producer/json/index/period/month/empties/'+empties+'/fields/'+fields+'/start/'+start+'/end/'+end+'',
async: false,
success: function(returned_values) {
$.each(returned_values.aaData, function(index, item) {
if (item[2] == 'EUR') {
EUR_share_cost += parseFloat(item[5]);
EUR_total_cost += parseFloat(item[3]);
} else if (item[2] == 'USD') {
USD_share_cost += parseFloat(item[5]);
USD_total_cost += parseFloat(item[3]);
} else if (item[2] == 'GBP') {
GBP_share_cost += parseFloat(item[5]);
GBP_total_cost += parseFloat(item[3]);
}
});
}
});
$('#EUR_share_cost').html(EUR_share_cost);
$('#USD_share_cost').html(USD_share_cost);
$('#GBP_share_cost').html(GBP_share_cost);
}
});
When you're in $.each(), the callback has 2 parameters, the first is the index (that incrementing number you're seeing), the second is the actual item, you'd actually want something like this:
$.each(returned_values || {}, function(index, item) {
console.log(item);
});
I think overall you're looking for this:
var eur_total = 0;
$.each(returned_values && returned_values.aaData || {}, function(index, item) {
if(item[2] == "EUR") eur_total += parseFloat(item[3]);
});
$('#EUR-total').val(eur_total);
This would total up the third column...not sure which column you're after (maybe 5th?), you can give it a try here.
The first part of $.each is the index, the second part is the data see the documentation for details.
Your code should instead look like this:
$.ajax({
url: '/area/json/index/period/month/',
async: false,
success: function(returned_values) {
console.log(returned_values);
$.each(returned_values || {}, function(index,item) {
console.log(item);
});
}
})