[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);
});
}
})
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);
}
});
}
Hey guys so am testing this cracker am working on via localhost to see if i can do it really since am bored and want to do something so i thought about this but may i ask why break and continue arnt working its a for loop isnt it?, So it should work.
Edit:
Forgot to mention that the code doesnt even work when i added the break and continue.
Any help is great thanks.
function doTest() {
var html_next;
var user_l = document.getElementById("users");
var pass_l = document.getElementById("pass");
if (user_l.value == "") {
alert("The username field cant be empty!")
} else if (pass_l.value == "") {
alert("The password field cant be empty!")
}
var message = document.getElementById('status_1');
var user_l_s = user_l.value.split("\n");
var pass_l_s = pass_l.value.split("\n");
for (var i = 0; i < user_l_s.length; i++) {
num_users++;
for (var j = 0; j < pass_l_s.length; j++) {
$.ajax({
url: 'posttest.php',
type: 'GET',
data: {'users': user_l_s[i], 'pass': pass_l_s[j]},
dataType: 'text',
async: false,
success: (function (i, j) {
return function (response) {
html_next = response;
if (html_next.indexOf("Failed") > -1) {
continue;
} else if (html_next.indexOf("Cracked") > -1) {
break;
} else if (html_next.indexOf("DELETED") > -1) {
break;
}
}
})(i, j),
beforeSend: function () {
message.innerHTML = "Cracking Test...";
}
});
}
}
message.innerHTML = "Done...";
}
It is because you are sending an Async request to your server. Which means your server is handling multiple requests and it is not necessary that every request gets responded to in the same time.
What you are looking for is sequential code that can process your data all at once.
You should try async:false and then try
You have to use success callbacks, you just need to use other logic. Instead for loops, call to a function when the ajax success is complete. This function have to register the changes and, if necessary, stop or keep working.
Here is an example that I used with another SO user but the logic and the idea are the appropriate. Instead of using loops, we wait for each success callback to keep working.
var MyApp = {
Scripts: {
ToLoad: [
'/path/to/script1.js',
'/path/to/script2.js',
'/path/to/script3.js'
],
Loaded: 0
},
DoTheJob: function(){
if( this.Scripts.ToLoad.length == this.Scripts.Loaded ) {
// do some stuff
return;
}
$.getScript(this.Scripts.ToLoad[this.Scripts.Loaded], function(){
MyApp.Scripts.Loaded++;
MyApp.DoTheJob();
});
}
};
$(function(){
MyApp.DoTheJob();
});
Here is the jsFiddle
This should do it..
You can even try it out with async = true
I think so it should work with it too
function doTest() {
var html_next;
var user_l = document.getElementById("users");
var pass_l = document.getElementById("pass");
if (user_l.value == "") {
alert("The username field cant be empty!")
} else if (pass_l.value == "") {
alert("The password field cant be empty!")
}
var message = document.getElementById('status_1');
var user_l_s = user_l.value.split("\n");
var pass_l_s = pass_l.value.split("\n");
for (var i = 0; i < user_l_s.length; i++) {
num_users++;
function makeReq(pass_l_s, index) {
var index = index || 0;
$.ajax({
url: 'posttest.php',
type: 'GET',
data: {
'users': user_l_s[i],
'pass': pass_l_s[index]
},
dataType: 'text',
async: false,
success: (function(i, index) {
return function(response) {
html_next = response;
if (html_next.indexOf("Failed") > -1) {
index += 1
if (index < pass_l_s.length)
makeReq(pass_l_s, index)
// continue;
} else if (html_next.indexOf("Cracked") > -1) {
// break;
} else if (html_next.indexOf("DELETED") > -1) {
// break;
}
}
})(i, index),
beforeSend: function() {
message.innerHTML = "Cracking Test...";
}
});
}
makeReq(pass_l_s)
}
message.innerHTML = "Done...";
}
I've json like this. in that json there is object name tipe and I want to sum act_qty1, act_val1, acvqty, acvval, budqty, budval, cm_val1, cm_val2, cm_val3 in the same tipe(e.g. sum them where their tipe is "ESL"). How to sum that in javascript? can it done with loop?
here is what I've made so far:
function detail(kodenegara, koderesult)
{
$.mobile.showPageLoadingMsg();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.greenfields.co.id:502/Service1.svc/"+kodenegara,
dataType: "json",
success:function(data){
var result = koderesult;
var details = "";
for (i = 0; i < data[result].length; i++){
$("#"+data[result][i].tipe).empty();
}
for (i = 0, types={} ; i < data[result].length; i++){
$("#"+data[result][i].tipe).append("<tr>"+
"<td>"+data[result][i].mc+"</td>"+
"<td>"+data[result][i].value3+"</td>"+
"<td>"+data[result][i].value2+"</td>"+
"<td>"+data[result][i].value1+"</td>"+
"<td>"+data[result][i].avgqty+"</td>"+
"<td>"+data[result][i].budqty+"</td>"+
"<td>"+data[result][i].budval+"</td>"+
"<td>"+data[result][i].acvqty+"</td>"+
"<td>"+data[result][i].acvval+"</td>"+
"</tr>").trigger('create');
//----------------------------------//
// HERE IS what I've made TO SUM THE VALUES //
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
for(i = 0; i < data[result].length; i++) {
if(data[result][i].tipe == 'ESL')
{
//how to summing data[result][i].cm_val3 where data[result][i].tipe == 'ESL'
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
}
}
}
//show the page
$.mobile.changePage("#detail_"+kodenegara, "slide", false, true);
},
error: function () {
alert("ERROR");
}
});
}
I don't know how to write the right looping for summing the value while tipe is "ESL" (or "ESL1L" or "WHP" or else). if I use this:
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
that only sum the last array. how to write the right looping to sum with that condition?
Here come a working fiddle
http://jsfiddle.net/xKJn8/1/
var SumByTipe = {};
for(i in data.GetReportIdResult){
var currtipe = data.GetReportIdResult[i].tipe;
if (currtipe){
if (currtipe in SumByTipe){
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
SumByTipe[currtipe][j + '_total'] += parseFloat(data.GetReportIdResult[i][j]);
}
}
}else{
var firstSum = {};
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data.GetReportIdResult[i][j]);
}
}
SumByTipe[currtipe]=firstSum;
}
}
}
console.debug(SumByTipe);
That should do the trick :
var sum_cm_val3=0;
for (var i=0;i<data[result].length;i++) {
if (data[result][i].tipe == "ESL") {
var cm_val3 = data[result][i].cm_val3;
if (parseInt(cm_val3)==cm_val3) {
sum_cm_val3 += parseInt(cm_val3);
}
}
}
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/
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();