How to access values of localStorage.getItem(JSONObj)
var result = JSON.parse(localStorage.getItem("resultData")); // ---In Ajax SuccessCallBack I have written var parseResult = JSON.stringify(result);localStorage.setItem("resultData",parseResult); ---
alert("Result :"+result); // I get proper result here
var obj_res = result.getTest_Data; // PHP - $data['getTest_Data'] = $query->result(); ----// tried with result.getTest_Data[0] , result.["getTest_Data"]
//alert(obj_res);// Undefined
$("#txtTTDNo1").val(obj_res.QC_TTDNo1); // Assigning Value to Text box
Getting error :
"Can not read property "QC_TTDNo1" of undefined.
Resolved. I had to again parse JSON as I was JSON.stringify() while localStorage.setItem("")...... var data1 = JSON.parse(result); var data = data1.getTest_Data;
Related
I am trying to create a global variable of parsed json data.
I want to use the global variable in other functions
The json parsing works great but I am having no luck with the global variable creation
async function GETELEMENTS(url) {
var response = await UrlFetchApp.fetch(url);
var responseText = await response.getContentText();
var responseJson = JSON.parse(responseText);
var elementKeys = Object.keys(responseJson.elements[0]);
var data = responseJson.elements.map(e => elementKeys.map(f => {
return e[f] instanceof Array ? e[f].join('|') : e[f];
}));
data.unshift(elementKeys);
if(data.length==0)
return;
}
var cache = CacheService.getScriptCache();
cache.put('A', data);
var cache = CacheService.getPublicCache();
return data;
}
where cache.get('A') is esseintaly SpreadsheetApp.getActive().getDataRange().getDisplayValues(); of the returned data
Then in a different function, I want to use
myotherfunction(cache.get('A'));
You can declare data outside of every function and it will automatically be a global variable.
Minimal reproducible example:
var data;
function GETELEMENTS() {
data = 'I was defined!';
}
function myotherfunction(){
Logger.log(data); // -> output: null
GETELEMENTS();
Logger.log(data); // -> output: I was defined!
}
If you execute myotherfunction, after the line GETELEMENTS() the data will have the value I was defined! defined in GETELEMENTS().
I have been trying to figure out to insert the JSON response into google Sheet in Google Apps Script with below code but for some reason I am getting error while trying to run.
please see screenshot and below code.
function myFunction() {
var key_67 = 'YYYYYYYYYYYYYYYYYY';
var ss_67 = SpreadsheetApp.openById(key_67);
var sheet_67 = ss_67.getActiveSheet();
sheet_67.getRange('A1:AZ10000').clearContent();
var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet';
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
var stats=[]; //create empty array to hold data points
//The following lines push the parsed json into empty stats array
stats.push(data.Yearly_Sales); //temp
stats.push(data.Email); //dewPoint
stats.push(data.Phone); //visibility
//append the stats array to the active sheet
sheet_67.appendRow(stats)
}
So your JSON response based on postman app is
var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","Potentially":50,"State":"NY","ZipCode":"10036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":"New York","Name":"Arfater Rahman"}]};
When I use that response as is:
function JsonResponse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","Potentially":50,"State":"NY","ZipCode":"10036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":"New York","Name":"Arfater Rahman"}]} '
var data = JSON.parse(json);
Logger.log(data);
}
I get the same error as you:
SyntaxError: Unexpected token: v
Which leads me to believe your response from API has this term var zohoipekuetview65 (Not really sure as to why? a bug perhaps)
The below code splits the response string to give you the JSON response only
function trialParse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","Potentially":50,"State":"NY","ZipCode":"10036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":"New York","Name":"Arfater Rahman"}]} '
Logger.log(JsonResponse(json))
}
function JsonResponse(response){
Logger.log(response)
var json = response.split("=")[1]
var data = JSON.parse(json);
Logger.log(data);
return data
}
Just call the above function in your code using var data = JsonResponse(json)
Final Note: As mentioned by Jordan Rhea you can use Logger.log(json) to output the response to your logs. To view your logs goto Views>Logs, it will show you the response you receive from Api.
from controller Json is returned and in function i get an object which contains
{
"readyState":4,
"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{
"Success":0,
"Failed":0
},
"status":200,
"statusText":"OK"
}
How can I take Success and Failed values?
data.Successand JSON.parse(data) is not working
You dont need to parse that because that IS already an object:
var obj = {"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}","responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"};
var failed = obj.responseJSON.Failed;
var success = obj.responseJSON.Success;
var json_data = '{"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"}';
var obj = JSON.parse(json_data);
alert(obj.responseJSON.Success); // for success that in responseJSON
alert(obj.responseJSON.Failed);
Thanks :)
I am getting an error in my .ajax() function when attempting to pass in the checkboxes
Here is the code:
if(typeof($post) !== 'undefined'){
var $fname = $($post).attr('name').toString();
var data = {$fname : []};
alert($post);
alert($fname);
$($post + ":checked").each(function() {
data[$fname].push($(this).val());
});
}else{
var data = null;
}
The error I am getting in firebug is: data[$fname].push($(this).val()); is undefined
$post is just a class name passed into the function.. in this case it's .del-checked
The alerts sucessfully alert me the class name, and the checkbox name... in this case it's del[]
How can I get this to work in order to pass it to the data option of $.ajax?
Because you can not use a variable as a key when creating a new object
var data = {$fname : []};
is the same thing as doing
var data = {"$fname" : []};
You need to create the object and add the key with brackets
var data = {};
data[$fname] = [];
You can't use variables as keys unless you use bracket notation
if (typeof($post) !== 'undefined'){
var $fname = $($post).attr('name');
var data = {};
data[$fname] = [];
$($post).filter(":checked").each(function() {
data[$fname].push( this.value );
});
}else{
var data = null;
}
What about:
var data = $($fname).serialize();
I'm trying to merge two objects I receive as JSON via Ajax, but I can not access the variable and declaring it global. What am I doing wrong?
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
post.done(function( data ) {
postdata = jQuery.parseJSON(data);
});
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
postwatch.done(function( data ) {
postwatchdata = jQuery.parseJSON(data);
});
var postmerge = $.extend(postdata,postwatchdata);
console.log(postmerge);
The answer of postdata = jQuery.parseJSON(data) should be:
{"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be:
{"respwatch":"needlogin"}.
But to access the console, instead of getting postdata and postwatchdata merged, I get an empty object.
Object {} product.js:61
Edit:
I want when post and postwatch done, use data in product function.
The answer of postdata = jQuery.parseJSON(data) should be: {"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be: {"respwatch":"needlogin"}.
function product(data){
var obj = jQuery.parseJSON(data);
if (obj.resplike=='like'){
var respuesta = 'No te gusta';
}
else if(obj.resplike=='dislike'){
var respuesta = 'Te gusta';....blabla
I want to get in obj: {"resplike":"needlogin", "respwatch":"needlogin"}
You cannot handle the result of an asynchronous call like that. All operations done on a async function call must be done within the callbacks of that async method. read more about this in answer
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
$.when(post, postwatch).then(function(arg1, arg2){
var postmerge = $.extend(arg1[0], arg2[0]);
console.log(postmerge);
})
Also since you need to wait for the responses from two different requests you can use $.when() which will back the success handlers once all the passed promises are resolved.