adding JSON length - javascript

I have a function that is called multiple times which uses jquery to fetch different JSON from an API.
I have been trying to get a cumulative count of part of that JSON. Here is sort of what I have:
getTheData(aBlah,bBlah,cBlah);
getTheData(aStuff,bStuff,cStuff);
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
console.log(data.subdata.length);
'the rest of the code'
});
}
I am trying to get a cumulative total of data.subdata.length but I'm not sure how to go about getting it.

This is a classic use case for closures:
var closure = function(){
var counter = 0;
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
counter += data.subdata.length;
'the rest of the code'
});
}
function getcount(){
return counter;
}
return {
getTheData:getTheData,
getcount:getcount
}
};
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
This helps control the scope of the counter variable. So you can do things like:
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
//counter in the new closure is zero
var newClosure = closure();
newClosure.getTheData(aBlah,bBlah,cBlah);
newClosure.getTheData(aStuff,bStuff,cStuff);
var totallyNewCount = myClosure.getcount();

Related

Looping incorrect in for each loop in jquery

I am pushing na element into a javascript array while it is in for each loop. but the loop is not as expected.
Code:
//lets say the length is 1 for array id.If its in error it has to loop 2 times, but looping only once
$.each(id, function(i, itemI) {
$.ajax({
type: "GET",
url: url1.trim(),
dataType: "json",
success: function(data) {//do something
},
error: function(xhr,status){
//push an element into array here
id.push("something");
}
});
})
As per doc, $.each takes the length property of object/array initially and iterate until it meet the length.
You can do like this.
var id=0, req = makeReq(id), makecalltimeout;
function makeReq(id)
{
id = id || "something"; //If id is undefined during first call.
var data = {id:id};
$.ajax({
type: "GET",
url: "google.com",
dataType: "json",
data:data,
success: function(data) {//do something
},
error: function(xhr,status){
clearTimeout(makecalltimeout);
makecalltimeout = setTimeout(makeReq(Math.floor(Math.random()*10)),1000)
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here I will make the request when it fails recursively with a time interval of 1 second. Just to send random data in the params, I have used Math.floor(Math.random()*10. You can replace with what you like.

Send php array to jquery ajax and make a each loop from that array

hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file
here is my php example
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
then here is my ajax
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
// here i want to read the array and make a loop for each element
},
});
thanks if you can help me
try basic for loop with count using length This .. this should help surely.
function ajax_test()
{
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i]);
}
}
});
}
Try a for loop to loop the records
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
var record;
for(record in response)
{
console.log(response[record]);
});
},
});
Please use below code :
$(response).each(function(key,value){
console.log(value);
});
Here each loop of response array and value get ('jazz',rock,...etc).
try see this, clear solution for your question
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.each : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. Reference documentation
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
//Check if the response is in expected JSON format.
var flag = isJSON(response);
if(flag === true)
{ response = JSON.parse(response); }
//Iterate the Array using for each loop of jquery
$.each(response, function( index, value ) {
console.log( "Index : " + index + "Value : " + value );
});
} // End of success function
}); //End of Ajax
//JSON format check
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
You can get array indexes and values by using .each in jQuery as:
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
$.each(response, function(index,value)
{
console.log(index); // print all indexes
console.log(value); // print all values
});
},
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
$.ajax({ url: "music_list.php",
dataType: 'json',
cache: false,
success:function(response) {
for( res in response) {
document.getElementById('dat').innerHTML+=response[res]+"<br/>";
}
}
});
</script>

Creating An Array within AJAX Function Feeding Value Using For Loop

I have the following AJAX function that has 2 variables i.e. sTitle, sValue. I need these two variables to be added to an Array in the format of ArrayName[sTitle, sValue]. I have tried this using a for loop but couldn't get the result I expected. I'm hoping to use this array to draw a Google chart. The data source is an XML.
I'm trying to implement this For Loop and array within the AJAX Call.
So how can I solve this matter?
AJAX Function
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
You can do it like this
var values = [];
function callback(val) {
// Do something with the array here
};
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
values.push([sTitle, sValue]);
});
callback(values);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});

Javascript scope when using ajax post and functions in general

I'm relatively new to javascript, and I have a restful api I'm connecting to that returns me a json string, which I can parse properly like so:
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
success: function(output) {
var json = $.parseJSON(output);
for( var i = 0 ; i < json.response.length; i++ ){
times.push (json.response[i].time);
}
}
});
Inside of the success callback the variables in the array exist. I also have times array instantiated outside the ajax call function. But outside of the ajax call the array is empty. I'm sure it's a scoping issue. Can anyone give me a way to get the data from inside the array? Does the construct $.ajax({url:... , data:... , success: function(){}}); returns callback return value?
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
dataType: 'json',
success: function(output) {
times = [];
for( var i = 0 ; i < output.response.length; i++ ){
times.push (output.response[i].time);
}
},
complete: function(){
if(times.length > 0){ console.log(times); } else { console.log("times empty"); }
}
});

Parameter as function name

I am not sure if this is possible. I would like to pass in a function name as parameter like this
loadContent("http://test.com/", specialFunction);
specialFucntion is just a string :
function loadContent(href, functionIWant){
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
functionIWant + "()"; //So this would be treated as function
//and it actually calls specialFunction()
//is it possible for this?
}
});
}
How do I achieve this?
ADD-ON
Let's say, I would pass in an array of function names, how do I call it?
for(var i = 0; i < functionIWant.length; i++){
functionIWant[i]; // how? appeciate a lot :)
}
You can just do it with functionIWant()
Example using your provided snippet:
function loadContent(href, functionIWant)
{
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
functionIWant();
}
});
}
For your addendum
Assuming the following three functions you want to call
function foo() {alert("Foo")}
function bar() {alert("bar")}
function baz() {alert("baz")}
The best I can recommend if you're passed an array of function names as strings is to follow the advice here. Basically, you could just do it like this:
// Assuming FunctionIWant is an array of strings that represent function names
FunctionIWant = ["foo","bar","baz"];
...
for(var i=0;i<FunctionIWant.length;i++)
window[FunctionIWant[i]]();
If, however, FunctionIWant is an array of actual functions, for example, you can simply iterate over them and call them individually like so:
FunctionIWant = [foo,bar,baz] // note, these are not strings
for(var i=0;i<FunctionIWant.length;i++)
FunctionIWant[i]();
In most cases, you'll be better off assigning the function rather than as a string
If you want to try to call the function represented by a parameter, simply call it as if that were the name of the function:
function loadContent(href, callback)
{
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
callback();
}
});
}
I am guessing that functionIWant is a string, not a reference to a function [You should make that clear when asking the question]
If that is the case, you want
window[functionIWant]();
That will work if the function is in the global scope. It would be better that you pass in the reference to the function or if you namespaced your functions.
var myFuncs = {
foo : function(){ alert("asdf"); },
bar : function(){ alert("qwerty"); }
};
var functionIWant = "foo";
myFuncs[functionIWant]();
for example you have two functions,
var function1 = function( value ) {
console.log( "foo: " + value );
};
var function2 = function( value ){
console.log( "bar: " + value );
};
and in functionIWant array you have name of function,
function loadContent(href, functionIWant)
{
$.ajax({
type: "GET",
url: href,
dataType: "json",
success: function(res, textStatus, xhr) {
helper();
var callbacks = $.Callbacks();
for(var i = 0; i < functionIWant.length; i++){
callbacks.add( functionIWant[i] ); //on i=0 add function1
callbacks.fire( "hello" ); // will fire function1
}
}
});
}

Categories