Please look at this code on https://jsfiddle.net/safron6/9g98j68g/embedded/result/
I am trying to get the calculated result from the list of APIS and JSON code that is generated to show the precipIntensity. At the end of the code there is an alert and the code works in firebug but nothing is showing up. What may be the reason why the alert does not pop up?
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
});
totalPrecipSinceDate did not declared.
I can't access your hosted data source.
Replacing your current $.getJSON call with an $.ajax call should work:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.ajax({
type: 'GET',
url: darkForecastAPI,
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain") {
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
},
error: function(){
alert('failure');
}
});
});
I'm using an ajax request to post a new message to a database. The page auto loads elements from the database onload. I want to delete the elements and re-add them when a user makes a post to add the current most post to the top of the list and its not working. I'm not sure why. There is no console error but it doesn't remove them.
onload ajax call
$.ajax({
url : "/getposts/",
type : "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success : function(json) {
document.getElementById('output').innerHTML = (json['message']);
for (var index = 0; index < json['user_posts'].length; index++) {
var div_make_badassness = document.createElement('div');
div_make_badassness.id = json['user_posts'][index][3];
document.getElementById('post_section').appendChild(div_make_badassness);
document.getElementById(json['user_posts'][index][3]).innerHTML = "<div id=" + json['user_posts'][index][3] + ">" + "Title:" + json['user_posts'][index][1] + "<br>" + json['user_posts'][index][0] + " Chomps: " + json['user_posts'][index][2] + "</div>" ;
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
document.getElementById('output').innerHTML = "Request Failed.";
}
});
on submit ajax call
$.ajax({
url : "/makepost/",
type : "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
username: username,
post_title: post_title,
post_text: post_text,
},
success : function(json) {
document.getElementById('output').innerHTML = (json['message']);
var post_section = document.getElementById("post_section");
for (var index = 0; index < post_section.length; index++) {
post_section.removeChild(post_section.childNodes[index]);
}
div tag
<div id ='post_section'>
</div>
for (var index = 0; index < json['user_posts'].length; index++) {
console.log(json['user_posts'][index][3] + json['user_posts'][index][1] + json['user_posts'][index][2]);
var div_make_badassness = document.createElement('div');
div_make_badassness.id = json['user_posts'][index][3];
document.getElementById('post_section').appendChild(div_make_badassness);
document.getElementById(json['user_posts'][index][3]).innerHTML = "<div id=" + json['user_posts'][index][3] + ">" + "Title:" + json['user_posts'][index][1] + "<br>" + json['user_posts'][index][0] + " Chomps: " + json['user_posts'][index][2] + "</div>" ;
}
Because you're using jQuery, I'll just do it in jQuery.
// Will remove any html in "post_section" and add in the new posts
function updatePostSection(user_posts) {
var post_section = $('#post_section');
post_section.html(''); // Remove all html contents inside
for(var i = 0; i < user_posts.length; i++) {
var div = $('<div>');
div.attr('id', user_posts[i][3]);
div.html("Title:" + user_posts[i][1]);
post_section.append(div);
}
}
In the success ajax function you can do something like...
// ...
success : function(json) {
updatePostSection(json['user_posts']);
},
// ...
Then you should be able to use it for both your getposts and makepost ajax calls assuming the json is the same structure.
Update: There are ways to optimize this so you're only writing to the dom once, but this is just an example.
i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}
I want to get the value of "status" from data in the code below,
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
$("<span class=\"label label-success\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});
Following is some part of the console.log result:
key: 2014-11-11
value: {"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
I want get the value of "status" i.e 0, as seen in the above result, in order to include it in the for loop (for (var key in data) {...}) to change the class 'label-success' to 'label-failure' if the status is 0. Could you help me?
Hello maybe I am wrong but
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
returns the whole data object in string format when you say JSON.stringify(data);
You want the value which is returned when you give data a specific key to read values from:
console.log('key: ' + key + '\n' + 'value: ' + data[key]);
EDIT: Im not sure if data[key] will return a [object Object]... if it does try JSON.stringify(data[key])
I would also suggest Itterating through data with the
for(var i = 0; i < data.length; i++){}
this makes it readable and is measured the most performant way of extracting data.
EDIT nr 2:
This is your object:
{"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
this is a bit nested, so try to get an overview of what you have:
data = {
"2014-11-11": [],
"2014-11-12": []... }
This object has a length method that returns the length of your object. this allows you to itterate over the Data Object will give you "2014-11-11" as key and with this key you can access your values like this: data[key] this will return your array...to read data from your array you will have to itterate again data[key][i]... now you can read the data inside each array element like this
data[key][i]["status"];
Hope this helped somehow... cant be bothered to write all this code :D
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
var status = data['status'];
var klass = status === 0 ? 'label-failure' : 'label-success';
$('<span class="label '+klass+'">' + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
Try this code instead.
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
for (var i in data[key]) {
$("<span class=\"label " + ((data[key][i] === "0") ? "label-failure" : "label-success") + "\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
}
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});
OK I am building something that makes an ajax request to one server where it determines the url it needs to then make a new ajax request to another place. Everything is progressing thanks to all the help at SO =) .. however I am stuck again. I am struggling with getting the variables to return to the different functions as I need. The second (jsonp) request returns a json function which looks like :
jsonResponse(
{"it.exists":"1"},"");
and my code...
var img = "null";
var z = "null";
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
$(data).find("ITEM").each(function()
{
query = $("SKU", this).text();
query = 'http://domain.com/' + query + '?req=exists,json';
img = $("SKU", this).text();
img = '<img src="http://domain.com/' + img + '">';
var date =$("LAST_SCAN" , this).text();
$.ajax({
url: query,
dataType: 'jsonp'
});
$("table").append('<tr>'+'<td>' + (date) + '</td>' + '<td>' + (z) + '</td>');
});
}
});
});
// function required to interpret jsonp
function jsonResponse(response){
var x = response["it.exists"];
// console.log(x);
if (x == 0) {
console.log("NO");
var z = "NO IMG";
}
if (x == 1) {
console.log(img);
//this only returns the first image path from the loop of the parseXml function over and over
var z = (img);
}
return z;
}
So I guess my problem is a two parter.. one how do I get the img variable to loop into that if statement and then once that works how can I return that z variable to be used in the first xml parser?
Try this synchronous approach:
var itemQueue = [];
$(document).ready(function ()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
itemQueue= $(data).find("ITEM").map(function ()
{
return {
sku: $("SKU", this).text(),
date: $("LAST_SCAN", this).text()
};
}).get();
getNextItem();
}
});
});
function getNextItem()
{
var item = itemQueue[0];
var query = "http://domain.com/" + item.sku + "?req=exists,json";
$.ajax({
url: query,
dataType: 'jsonp'
});
}
function jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
var x = response["it.exists"];
var z = x == "0" ? "NO IMG" : "<img src=\"http://domain.com/" + item.sku + "\">";
$("table").append("<tr><td>" + item.date + "</td><td>" + z + "</td>");
}
Store 'date' in a global variable, and move the logic to append HTML elements into the jsonResponse function. You cannot return control flow from jsonResponse because it's called asynchronously, but you can continue doing anything you'd like from that function.