json couldn't change the dataWithLabels - javascript

Please can you help see the code. I would like to change the title name from 'Jason' to the temperature written in the JSON file.
var dataWithLabels = [
{
"title":"Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for(var i=0;i<1/*dataWithLabels.length*/;i++){
var statistic = data.current_observation;
dataWithLabels[i]['title']= statistic.temp_c;}}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
alert(dataWithLabels[0]['title']);
http://codepen.io/wtang2/pen/bEGQKP
It's NOT a duplicate, I am trying to replace the result from JSON file to title of dataWithLabels object

Since I don't know, if your JSON you are requesting is correct, I just assume it is. Still, if you like to see, what is happening in dataWithLabels after your Ajax-Request, you need to rewrite the function a little:
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']);
}
}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
Now, the status of dataWithLabels is alerted AFTER you insert the statistic.temp_c. Your code always alerts the state BEFORE the Ajax-request.
Hope that helps!

This is because AJAX request works asynchronously so you need to alert the result only after the AJAX request is completed for that you can do
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']); // Alert only after data is received
}
}
});

Related

Why won't all the data get displayed on the browser even though all data is being displayed in console.log()?

I'm using an $.ajax(); request to make a call to my controller. Inside the console.log();, it's correctly displaying all of the data coming in but when I try to display it on the browser via $('#displayCoins').text(item.oldCoins); - only the very last piece of data if being displayed instead of all of the data.
What am I doing wrong and how can I go about rectifying this in terms of displaying all of the data on the browser?
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
$('#displayCoins').text(item.oldCoins);
});
}
});
The problem that you are having is you are REPLACING the text every time through the loop instead of appending it.
One solution is to append the data to an array, then output it to the DOM via a single join.
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
oldCoins = [];
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
oldCoins.push(item.oldCoins);
});
$('#displayCoins').text(oldCoins.join("\n"));
}
});

adding JSON length

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();

JSON.parse : why this doesn't work

I got a JSON :
$.ajax({
type: "POST",
url: myUrl,
success: function (result) {
var data = JSON.parse(result);
for (var i = 0; i < data.poles.length; i++) {
....
What i see in debugger is that :
data = "{"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"},....],"poleNumber":48}
But i get a message saying that data.poles is not defined
What do i miss?
Is Json ok?
{"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"}],"poleNumber":48}
EDIT:
Ok, if you have this JSON:
data = {"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"}],"poleNumber":48}
you can make data.poles perfectly. delete the first ", you have a wrong json, so you will never parse
"{"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"}],"poleNumber":48}

How to send array in AJAX using JSON

I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?
I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:
Uncaught TypeError: Illegal invocation
but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.
//first thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
console.log(cu[j].value);
i++;
}
var dynamic_account_value = JSON.stringify(cu);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
}
});
//2nd thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
cu2.push(JSON.parse(cu[j].value));
i++;
}
var tilinrot_lisa = JSON.stringify(cu2);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
}
});
First, give them something that makes selection easier, like a common class. Second, use jquery serialize
$.ajax({
url : "foo",
data : $(".bar").serialize(),
success : function(response) {}
})
Try this code snippet, Try to send just one variable then go for another & use content type.
u can use //console.log(JSON.stringify(cu)); to view what's inside.
jQuery.ajax({
type: 'post',
dataType: 'json',
data: {your_var:JSON.stringify(cu)},
contentType: "application/json"
});

Why doesnt this javascript code work?

I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....

Categories