i have many pieces of code like:
<script type="text/javascript">
dojo.query("body").delegate("#input0 > select.estatistica", "onchange", function(evt){
dojo.xhrPost({
url: "drop2.php",
handleAs: "json",
postData: "data=" + $(this).val(),
preventCache: true,
load: function(json) {
$m0 = [];
for (var i = 1; i < 10; i++) {
$m0.push(parseFloat(json[i]["valor" + i]));
}
dojo.addOnLoad(refreshChar0);
}
});
});
</script>
<script type="text/javascript">
dojo.query("body").delegate("#input1 > select.estatistica", "onchange", function(evt){
dojo.xhrPost({
url: "drop2.php",
handleAs: "json",
postData: "data=" + $(this).val(),
preventCache: true,
load: function(json) {
$m1 = [];
for (var i = 1; i < 10; i++) {
$m1.push(parseFloat(json[i]["valor" + i]));
}
dojo.addOnLoad(refreshChart1);
}
});
});
</script>
i tried this loop, but i am not sure about the script. Probably i have syntax errors.
<script type="text/javascript">
for(x=0; x<10; x++) {
dojo.query("body").delegate("'#input'+x+'> select.estatistica'", "onchange", function(evt) {
dojo.xhrPost({
url: "drop2.php",
handleAs: "json",
postData: "data=" + $(this).val(),
preventCache: true,
load: function(json) {
$m+x = [];
for (var i = 1; i < 10; i++) {
$m+x.push(parseFloat(json[i]["valor" + i]));
}
dojo.addOnLoad(refreshChart+x);
}
});
});
}
</script>
thanks
to create a variable name dynamicaly you have to use bracket notation
e.g: this['$m'+x] or window['$m'+x] will create a variable called $m1 where x = 1
try:
window['foo' + 'bar'] = 'hello';
alert(foobar);
By the looks of $m+x I'm guessing that you're trying to create a variable dynamically such as $m0 to $m9 based on iterating from 0 - 10. You can't do that in Javascript as far as I'm aware it will give you an error. I suggest instead of creating a dynamic variable sort of thing why not fill the values inside an array based on the indexes of x.
Here's something:
var $m = [];
for(x=0; x<10; x++)
{
// some of your codes here ...
// make $m[x] an array
if (typeof $m[x] == "undefined")
$m[x] = [];
// some of your codes here...
for (var i = 1; i < 10; i++)
{
// of course you need to change this to what you need to push
$m[x].push(i);
}
}
console.log($m[0]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
So basically $m will be an array with arrays. I don't know if my guess is right but I hope it gives an idea.
Related
I feel like im close, i need to return my filtered json object data and be able to use it in future functions. My main issue im having is its saying "callback is not a function". I used the second method in the top response here How do I return the response from an asynchronous call?
Thanks!
function randomFxn(callback){
var newObj = {};
$.ajax({
type: 'GET',
url: 'https://api.imgur.com/3/album/' + imgurID + '/images',
headers: {'Authorization': 'Client-ID '+ key},
success: function(jsonData){
var nameArr = ['mario', 'luigi', "...some other stuff"];
var counter = 0;
var inCounter = 0;
for(var i = 0; i < nameArr.length; i++){
for (var j = 0; j < 8; j++){
newObj[nameArr[counter]+j] = jsonData.data[inCounter].link;
}
counter++;
}
// $('body').html(`<pre>${JSON.stringify(newObj, null, '\t')}</pre>`);
console.log(newObj);
callback(newObj);
}
});
}
I guess, you have to call randomFxn like so:
randomFxn(function(result) {
console.log("got result", result);
});
The error is not in this function - it is how you are calling this function.
There are two ways to fix the problem, depending upon the logic of your application. You could change your function to this:
function randomFxn(){
var newObj = {};
$.ajax({
type: 'GET',
url: 'https://api.imgur.com/3/album/' + imgurID + '/images',
headers: {'Authorization': 'Client-ID '+ key},
success: function(jsonData){
var nameArr = ['mario', 'luigi', "...some other stuff"];
var counter = 0;
var inCounter = 0;
for(var i = 0; i < nameArr.length; i++){
for (var j = 0; j < 8; j++){
newObj[nameArr[counter]+j] = jsonData.data[inCounter].link;
}
counter++;
}
// $('body').html(`<pre>${JSON.stringify(newObj, null, '\t')}</pre>`);
console.log(newObj);
}
});
}
Or, wherever you call randomFxn, you need to pass another function as a parameter:
randomFxn(function() {
// do something here
});
//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}
I need your help. I get hash tags data from Tumblr via ajax and I loop through them to output them. Before I output the tags I want to do some filtering, and in the output if I have 4 of the same hash tag I need to only output it once.
Here is an example where without the filtering.
jsFiddle
$.ajax({
url: "http://api.tumblr.com/v2/blog/testhermes.tumblr.com/posts",
dataType: 'jsonp',
data: {
api_key : "d01TZzpbq12cD7Zv7dM4EwLndkAAIEsExnLl9PNvsHYuyuDwKq"
},
success: function(results){
var posts = results.response.posts;
var text ='';
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = a[j];
text += ''+ c +'<br>';
$("body").append(text);
}
}
}
});
thank you
You just have to hold value in array and check every time you insert item whether it exist in array or not.
$.ajax({
url: "http://api.tumblr.com/v2/blog/testhermes.tumblr.com/posts",
dataType: 'jsonp',
data: {
api_key : "d01TZzpbq12cD7Zv7dM4EwLndkAAIEsExnLl9PNvsHYuyuDwKq"
},
success: function(results){
var posts = results.response.posts;
var text ='';
var arr = [];
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = $.trim(a[j]);
if(jQuery.inArray(c, arr) == -1)
{
arr.push(c);
var text = ''+ c +'<br>';
$("body").append(text);
}
}
}
}
});
Here is JS FIDDLE link.
Simply keep track of tags you've already seen in an object, then only output the link if you haven't seen the tag before.
var seen_tags = {};
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = a[j];
if(!(c in seen_tags)) {
text += ''+ c +'<br>';
$("body").append(text);
seen_tags[c] = true;
}
}
}
i use a nice code to import csv data.
However, my variable seems to be somehow caught within the function so i cannot access it from other places in my .js ...
see my two alert functions in the code below.
Code copied from post(How to read data From *.CSV file using javascript?)
$(document).ready(function () {
$.ajax({
type: "GET",
url: "../recipes.csv",
dataType: "text",
success: function (data) {
processData(data);
}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 0; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
dataArray = (lines + "").split(';');
alert(dataArray[1]); // here it works
}
alert(dataArray[1]); // here it doesn't work: "ReferenceError: dataArray is not defined"
The dataArray variable that the function processData(...) uses exists only inside the function.
In order to use it outside the function you need to declare it. For example:
var dataArray = {};
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=0; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
dataArray = (lines + "").split(';');
alert(dataArray[1]);
}
$(document).ready(function () {
$.ajax({
type: "GET",
url: "../recipes.csv",
dataType: "text",
success: function (data) {
processData(data);
alert(dataArray[1]); // here it will return the data from processData(...)
}
});
});
What is the scope of variables in JavaScript?. Here is an interesting thread for variable scope in JavaScript.
Hi jquery/javascript gurus,
I am trying to use jquery ajax function to populate the dropdown, it works fine with FF, but IE give the javascript error snow below in the scrnshot. howver IE does get the data and selects it.
Am i doing something wrong?
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
$("#dropdown").val(curval);
}
});
}
You say val(curval) at the end of your function, but your function parameter is named currval with two Rs.
This worked!
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
try {
$("#dropdown").val(curval);
} catch(ex) {
setTimeout("$('#dropdown').val('"+curval+"')",1);
}
}
});
}