How do I access every index of a specific Array inside an AJAX object - ajax

I'm calling an ajax for giphy, with this code:
$.ajax({
url: queryURL,
method: "GET"
}). then(function(response) {
console.log(response);
when I look at the console log there's an object with the first property being data. Each index of data is another object, inside this object are two properties i'm trying to pull, rating and url. I want to be able to list the rating and url not just of a specific index, but every index in that data array. What would be the best way to do that? Currently I've tried a for loop
for (var i = 0; i<response.data.length;i++){
var dataIndex = response.data[i];
}
then <creating a variable something like>
var imgURL = response.data[dataIndex].url
but its not working.
Here's the entire code
function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
// for loop to create a variable for the index of the objects data
for (var i = 0; i < response.data.length; i++) {
var dataIndex = response.data[i];
}
// where the gif's will be dumped
var topicDiv = $("<div class='topic'>");
// rating of gif
var rating = response.data[0].rating;
console.log(rating);
// Creating an element to have the rating displayed
var pOne = $("<p>").text("Rating: " + rating);
// add to the rating element
topicDiv.append(pOne);
// retrieve the IMG of the gif
var imgURL = response.data[0].url;
var image = $("<img>").attr("src", imgURL);
topicDiv.append(image);
// put gif into topic-view div
$("#topic-view").prepend(topicDiv);
});
}

You can check that something is an object using $.isPlainObject and then read through its properties via:
for (key in object) {
var value = object[key];
//log
}
Or you can get the keys using Object.getOwnPropertyNames();. See this sample excerpt from MDN:
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

Related

Problem with scope when inserting results of ajax call into page code

I have data returned from an Ajax call, but need to pass variables into or out of the Ajax onSuccess function to insert the results into my page. I'm pretty sure this is a scope problem.
I posted a complicated question here yesterday, mostly about the Ajax part of this, and that part is now working - I'm getting the results back correctly. I could insert it into my page code in two ways, but one involves getting a variable value out of the onSuccess function; the other needs to get a variable value into it! I can't make either of them work. Here's a stripped-down version of the code:
var base = 'http://10.0.1.2:90/~dvds/';
// initialization routines
document.observe ('dom:loaded', function() {
// set up handler for variable numbers of selects
var addselects = $$('.addselect');
for (var i = 0; i < addselects.length; i++) {
var addselect = addselects[i];
addselect.onchange = newSelect;
}
});
// handler for adding new field to array
function newSelect() {
var thisid = this.id;
var newhtml;
var url = base + 'ajaxtest';
// send request to do the business
var myAjax = new Ajax.Request (url, {
method: 'post',
onSuccess: function (req) {
var xml = req.responseXML;
var id = xml.getElementsByTagName('id')[0].firstChild.nodeValue;
if (id) {
newhtml = '\t\t<li>\r\t\t\t<select class="addselect" name="newlist" id="newlist" />\r\t\t\t\t<option value="" selected="selected"></option>\r';
// loop
var newid, newname;
var ids = xml.getElementsByTagName('id');
var names = xml.getElementsByTagName('name');
for (var i = 0; i < ids.length; i++) {
newid = ids[i].firstChild.nodeValue;
newname = names[i].firstChild.nodeValue;
newhtml += '\t\t\t\t<option value="' + newid + '">' + newname + '</option>\r';
}
newhtml += '\t\t\t</select>\r\t\t</li>\r';
// alert (thisid);
$('thisid').up('ul').insert (newhtml);
}
else {
alert (’ng');
newhtml = '<li>No good.</li>';
}
},
onFailure: function() {
alert ('Script failure.');
newhtml = '<li>No good.</li>';
}
});
// alert (newhtml);
// if (newhtml) {
// this.up('ul').insert (newhtml);
// }
}
Having established the variable thisid as this.id, I don't understand why $('thisid') doesn't work in the line $('thisid').up('ul').insert (newhtml); - especially as the value of thisid does show up correctly in the alert I've put in for testing (commented out). Why is this? If I put newhtml into that alert instead it's also correct.
And given that that seems not to work, I tried the alternative of passing the value of newhtml out (having declared it at the top) and inserting it in the page in the last block of code that's commented out - but that doesn’t work either.
Where am I going wrong?

Submitting data to google sheet with multiple tab sheets

I'm referencing this article "How to Submit an HTML Form to Google Sheets…without Google Forms", it worked perfectly for me for only a Google Sheet with one tab.
Need help how to dynamically select what sheet tab the data should be written in the case the google sheet has multiple tabs. I'm using Ajax to submit google sheet btw.
Here's the call by the Ajax:
var $form = $('form#test-form'),
url = 'https://script.google.com/macros/s/MyScript/exec'
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
The code on google sheet web app
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
If there is a way to change the variable SHEET_NAME dynamically then I think it will be good. Thanks

javascript Unable to trigger image.onerror handler

Somehow I am unable to fire the onerror event or get the code in the onerror to work. This code is an attempt to collect a sequence of images in an array. I am using onerror event in order to mark the end of sequence and thus terminate the loop.
//definition of Slide object
function Slide(inpImage, imgCaption) {
this.inpImage = inpImage;
this.imgCaption = imgCaption;
}
window.onload = function() {
var defaultImage = img_slide.src; //This is a default file
//basically getting the file path and name of next image in the sequence
var nextImage = f_nextFile(f_path(img_slide.src),f_serial(img_slide.src));
//An array object which stores Slide Objects
arr_slides.push(new Slide(img_slide,img_slide.src));
while (defaultImage != nextImage){ //code to populate arr_slides array
var imgObj = new Image();
imgObj.src = nextImage;
arr_slides.push(new Slide(imgObj,nextImage));
//get the next image in the sequence of images
nextImage = f_nextFile(f_path(nextImage),f_serial(nextImage));
testImage = function(nextImage,defaultImage){
var tester=new Image();
tester.onerror = function () {
nextImage = defaultImage;
};
tester.onload = function () {
//do nothing
};
var loadNext = function() {
tester.src=nextImage;
};
loadNext();
};
testImage(nextImage,defaultImage);
}
alert("The number of images in array : " + arr_slides.length);
};

retrieve data from c# linq object to json to html

Retrieve code from json.
C#code:-
var collection = getsortcat.Select(x => new
{
idterm = x.IDTerm,
mvo = x.MVO,
pic = x.Pic,
said = x.SAid,
termactive = x.TermActive,
vid = x.Vid,
fvo = x.FVO,
eterm = x.ETerm,
edef = x.EDef,
buse = x.BUse,
bterm = x.BTerm,
idcat = x.TermCat,
items = x.TermCategory1.IDCat,
catname = x.TermCategory1.TermCategory1
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(collection);
return Json(output, JsonRequestBehavior.AllowGet);
Javascript Code:-
success: function (e) {
var txt = "'{ data :" + e + "}'";
var obj = eval("(" + txt + ")");
$('#pdata').append(obj.data[0]);
},
Not getting output. Please give me solution how to retrieve data from c# linq object to json to html?
First fix your controller action to get rid of any JavaScriptSerializers and manual plumbing code. Directly return the collection to the Json result:
var collection = getsortcat.Select(x => new
{
idterm = x.IDTerm,
mvo = x.MVO,
pic = x.Pic,
said = x.SAid,
termactive = x.TermActive,
vid = x.Vid,
fvo = x.FVO,
eterm = x.ETerm,
edef = x.EDef,
buse = x.BUse,
bterm = x.BTerm,
idcat = x.TermCat,
items = x.TermCategory1.IDCat,
catname = x.TermCategory1.TermCategory1
});
return Json(collection, JsonRequestBehavior.AllowGet);
Now inside the success callback the e parameter already represents an array of objects that were parsed. You don't need to call any eval. Directly access the elements (by index) and then the properties:
success: function (e) {
var txt = e[0].mvo;
},
you could also loop through the elements:
success: function (e) {
for (var i = 0; i < e.length; i++) {
var element = e[i];
alert(element.idterm);
}
},

titanium mobile:onload function called issue in json parsing

Hello friends,
I am developing an app in Titanium Studio sdk 1.8.1 using Google Place API to display category atm list & address in tableview so I use json parsing using this link but loader.onload function of getData method is not called immediately after send function of getData method in json parsing so its called after getDetailsData() function and also can't display address in tableview so please give me idea how to solve it.
Thanks in advance.
var lat ,lon ,radius , name , sensor , key , reference, address;
lat = '-33.8670522';//'23.042067';
lon = '151.1957362';//'72.530835';//
radius = '500';
name = title;
sensor = 'false';
key = 'AIzaSyDALrXHC4uMtfSrpCg6NHxqPhsLccLYPZE';
var rowData = [];
// getCategoryData using Google Place API
function getData()
{
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
var name = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
getDetailsData();
// Create a row and set its height to auto
var row = Titanium.UI.createTableViewRow({height:'auto'});
// Create the view that will contain the text and avatar
var post_view = Titanium.UI.createView({
height:'auto',
layout:'vertical',
top:5,
right:5,
bottom:5,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
// Create the label to hold the tweet message
var addressLabel = Titanium.UI.createLabel({
text:'Address',
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
nameLabel.text = name;
//addressLabel.text = placeAddress;
post_view.add(nameLabel);
post_view.add(addressLabel);
// Add the post view to the row
row.add(post_view);
// Give each row a class name
//row.className = "item"+i;
// Add row to the rowData array
rowData[i] = row;
//rowData.push(row);
}
//tableView.setData(rowData);
// Create the table view and set its data source to "rowData" array
var tableView = Titanium.UI.createTableView({data:rowData});
//Add the table view to the window
showWin.add(tableView);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
}
function getDetailsData ()
{
var loader1 = Titanium.Network.createHTTPClient();
Ti.API.log('getDetailsData');
var url = "https://maps.googleapis.com/maps/api/place/details/json?";
url = url + "reference=" + reference;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader1.open("GET",url);
// Runs the function when the data is ready for us to process
loader1.onload = function()
{
var detailsObj = JSON.parse(this.responseText);
Ti.API.log(detailsObj);
address = detailsObj.result.formatted_address;
Ti.API.log('Address:'+address);
phoneno = detailsObj.result.formatted_phone_number;
Ti.API.log('Phone No:'+phoneno);
};
//-- Network error
loader1.onerror = function(event)
{
Ti.API.info('Network error: ' + JSON.stringify(event));
};
// Send the HTTP request
loader1.send();
return address;
}
getData();
Dont't use the return in the second http request.
Pass the label object in the function like:
getDetailsData(addressLabel);
and set the text inside loader1.onload like this:
address = detailsObj.result.formatted_address;
addressLabel.text = address;

Resources