Checking for null XML data with JavaScript - javascript

I get data from XML. I need to check data and if data is null I must hide this.
How can I check?
<script>
downloadUrl("gxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var oid = markers[i].getAttribute("objectid");
var status = markers[i].getAttribute("status");
var title = markers[i].getAttribute("title");
var volume = markers[i].getAttribute("volume");
var kwh = markers[i].getAttribute("kwh");
var puser = markers[i].getAttribute("puser");
var ucomp = markers[i].getAttribute("ucomplate");
var udate = markers[i].getAttribute("udate");
var suser = markers[i].getAttribute("suser");
var scomp = markers[i].getAttribute("scomplate");
var sdate = markers[i].getAttribute("sdate");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "ObjectID:" + oid + " <br/> Title:" + title +" <br/>Status:" + status + " <br/>Volume:" + volume + " <br/> KWh:" + kwh + " <br/>User:" + puser + " <br/> User Date:" + udate + " <br/> User Complate :" + ucomp + " <br/>Super user:" + suser + " <br/> S .User Date:" + sdate + " <br/> S. User Complate :" + scomp + "<br/> Add/Edit";
</script>
// this data i get from xml. i`m need to chek this null or not null

You can simply do a if (!myVariable) check on any given variable. If that returns true (that is to say if the code enters the if body, then the data is null. What I would do is instead of doing this:
var oid = markers[i].getAttribute("objectid");
// ...
..."ObjectID:" + oid + "
Include your title in the variable, like this:
var oid = markers[i].getAttribute("objectid");
if (oid) {
oid = "ObjectID: " + oid;
}
and that way you can add oid directly to your string. If the value is null, adding it will have no effect because the variable will be empty. If there was a value, then the title will be appended and doing a + oid will append the title and value at the same time.

if ( !foo ) {
// foo is not set, it is null.
}

Related

Amchart4 not shown till end of Datatime From json file in parseend event

I looking for solution to shown all my data in amcharts4 , My data not shown exact and just sme out before them is shown , what is soltion for them ?
chart.dataSource.url ="/static/json/{{ Post.Datasource|safe }}.json";
chart.dataSource.parser = new am4core.JSONParser();
chart.dataSource.reloadFrequency = 5000;
chart.dateFormatter.inputDateFormat = "i";
var title = chart.titles.create();
//Funtion Date From and to
chart.dataSource.events.on("parseended", function(ev) {
var data = ev.target.data;
for (var i = 0; i < data.length; i++) {
var startdate = new Date(data[0]["DATETIME"]).toISOString().replace("T"," ").replace("Z","").replace(".000","");
var enddate = new Date(data[data.length -1]["DATETIME"]).toISOString().replace("T"," ").replace("Z","").replace(".000","");
}
title.html = (
"Data from :" + '<span class="colors"> ' +
startdate+ '</span> ' +
" to " + '<span class="colors">' +
enddate + '</span>'
);
});
Text shown less than exact lenght of data, also my title not refreshed
Moment library can convert data easy
starttime = moment(starttime).format("YYYY-MM-DD HH:mm:ss");

Javascript object set to another object is undefined

For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}

Resolve 'Parsing Error: Please check your selector. (line XX)' Javascript/AWQL

First off, let me say that I am not a developer, nor do I really code beyond basic HTML. So I appreciate your patience. :)
I'm working with a script that is for AdWords, but I believe it's more or less written in Javascript. (I've included the script below.)
Basically, I'm receiving the error message 'Parsing Error: Please check your selector. (line XX)' when I preview the script.
I've searched all around for hours and have yet to find a solution.
I think it may be that a query being returned contains either a single or double quote, and may be messing up the code? Though I can't actually prove that.
Also, yes, I was sure to update lines 17-21 with the correct details.
Any help would be much appreciated!
Thanks!
John
/*
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "example#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query); //THIS IS LINE 103 WITH THE ERROR
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
The area between SELECT and FROM is the selector. You're not selecting any fields with that query. That's happening because the headerNames array is empty. Verify the value of REPORT_SHEET_NAME

for in loop statement return undefined values

Need some help with this piece of a code. I am able to produce the results I want with the code in Working Code, but when I implement this code on another sheet (which is the master code) it does not work. scratching my head trying to figure this out
Here is the shared google spreadsheet with both full codes. Go to script editor.
Google Docs Link
Any help would be much appreciated. Thank you in advanced.
EDIT#3 Submit section of None Working Code
function submit(e){
var app = UiApp.getActiveApplication();
var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var projectname = e.parameter.projectname;
var projectid = e.parameter.projectid;
var projectmanager = e.parameter.projectmanager;
var salesrep = e.parameter.salesrep;
var duedate = e.parameter.duedate;
var projectphase = e.parameter.projectphase;
var disctype = e.parameter.disctype;
var mediatype = e.parameter.mediatype;
var encryptiontype = e.parameter.encryptiontype;
var password = e.parameter.password;
var quantity = e.parameter.quantity;
var specialinstructions = e.parameter.specialinstructions;
var update = "Colombo Save";
//var sheet = ss.getSheets()[0];
var uiData = [[
projectname,
projectid,
projectmanager,
salesrep,
duedate,
projectphase,
disctype,
mediatype,
encryptiontype,
password,
quantity,
specialinstructions,
update
]];
sheet.getRange(sheet.getLastRow()+1, 1, uiData.length, uiData[0].length)
.setValues(uiData);
var app = UiApp.getActiveApplication();
var result = {};
var numMembers = parseInt(e.parameter.table_tag);
result.members = [];
for(var i=1; i<=numMembers; i++){
var member = {};
member.firstName = e.parameter['fName'+i];
member.lastName = e.parameter['lName'+i];
member.company = e.parameter['company'+i];
member.address = e.parameter['address'+i];
result.members.push(member);
}
var htmlBody = 'Shipping Information: <br>'
for(var a in result.members) {
var member = result.members[a];
var fname = member.firstName;
var lname = member.lastName;
var company = member.company;
var address = member.address;
var timestamp = Utilities.formatDate(new Date(), "America/New_York", "MMMM dd, yyyy hh:mm:ss"); // Timestamp
var activeSessionuser = Session.getActiveUser();//Session.getEffectiveUser(); Get the current user in the spreadsheet
var emailAddress = 'test#email.com'; //Venue Colombo Team
var subject = "**Test Email** DVD Request Submitted - **Test Email**"+ projectname +" - "+projectid+" - "+ projectmanager;
/^var emailBody =*/
var emailBody =
"<br><font color=\"Blue\"><b><h2>Request Submitted</h2></b></font>"
+"<br/>Hi Venue Colombo Team,<br/>"
+"<br/>The following data room(s) will need a disc creation. Please begin bulk save data room and create ISO to upload to the FTP site:<br/>"
+"<br/><b>Project Name:</b> " + projectname
+"<br/><b>Project ID:</b> " + projectid
+"<br/><b>Project Manager:</b> " + projectmanager
+"<br/><b>Sales:</b> " + salesrep
+"<br/>" + htmlBody + 'Client Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Address: ' + address +'<br>'+'<br>'+
+"<br/>"
+"<br/><b>Phase:</b> " + projectphase
+"<br/><b>Disc Type:</b> " + disctype
+"<br/>"
+"<br/><b>Encryption:</b> " + encryptiontype
+"<br/><b>Password:</b> " + password
+"<br/><b>Quantity:</b> " + quantity
+"<br/>"
+"<br/><b>Client Due Date:</b> " + duedate
+"<br/>"
+"<br/><font color=\"Red\"><b>Special Instructions:</b></font> " + "<br/>"+ specialinstructions
+"<i><br/> <br/>This request was submitted by:</i> "
+"<br/><font color=\"blue\">Name:</font> " + activeSessionuser
+"<br/>Time Stamp: " + timestamp
+"<br/>"
+"———————————————————————————————"
+ //Line divider code —
"<br/>Venue Client Services"
+"<br/>United States: "
+"<br/>UK/International: "
+"<br/>France: "
+"<br/>Asia: ";
htmlBody += 'Client Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Address: ' + address +'<br>'+'<br>';
}
var optAdvancedArgs = {name: "Venue Client Services", htmlBody: emailBody};
//MailApp.sendEmail('fake#email.com', subject, '', optAdvancedArgs);
Logger.log(htmlBody);
Logger.log(emailBody);
var html = app.createHTML('First Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Client Address: ' + address);
app.add(html);
//dvdForm();
return app;
}
Here is the result on the Application
Here is the Logger logs
Logger.log(htmlBody);
Logger.log(emailBody);
I was finally able to figure out what the issues was with "for loop statement return undefined values"
I did not add a .addCallbackElement to the panel containing the form fields.

Getting hourly info from weather API

I am trying to access hourly info from a weather API.
The problem is its not quite working for me, and I am not 100% sure of how to gain access to the information.
This is the site I am working with, and the page on the hourly info.
http://www.wunderground.com/weather/api/d/docs?d=data/hourly&MR=1
I have a strong feeling it has to do with the way the access to variables...
This is my code:
<script>
jQuery(document).ready(function($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType : "jsonp",
success : function(parsed_json) {
//get the hourly info -- cant get hourly to work...
var month = parsed_json['hourly_forecast']['FCTTIME']['mon_padded'];
var day = parsed_json['hourly_forecast']['FCTTIME']['mday_padded'];
var year = parsed_json['hourly_forecast']['FCTTIME']['year'];
var time = parsed_json['hourly_forecast']['FCTTIME']['civil'];
var updated = month + "/" + day + "/" + year + " " + time;
var weather = parsed_json['hourly_forecast']['condition'];
var temp = parsed_json['hourly_forecast']['temp']['metric'];
var humid = parsed_json['hourly_forecast']['humidity'];
var wind_direction = parsed_json['hourly_forecast']['wdir']['dir'];
var wind_speed = parsed_json['hourly_forecast']['wspd']['metric'];
var wind_string = wind_direction + " " + wind_speed + " Km/h";
document.getElementById("weather").innerHTML = weather;
document.getElementById("temp").innerHTML = temp;
document.getElementById("hum").innerHTML = humid;
document.getElementById("wind").innerHTML = wind_string;
}
});
});
</script>
If you open the JSON file from that URL you will see that it does not contain "hourly_forecast" or "FCTTIME".
EDIT:
Open up the JSON file that you are downloading and look at what fields it is sending back to you. JQuery already does the hard part and parses it into an object model. Also, the javascript debuggers in Chrome is great at showing you the JSON object model. You can just set a breakpoint at the beginning of the "success" function and use the "Local Variables" window to explore the JSON object.
Here's your code after I updated it to use the correct field names from the JSON file...
<script>
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType: "jsonp",
success: function (parsed_json) {
var current_observation = parsed_json.current_observation;
var lastUpdated = current_observation.observation_time;
var weather = current_observation.weather;
var temp = current_observation.temp_c;
var humid = current_observation.relative_humidity;
var wind_direction = current_observation.wind_dir;
var wind_speed = current_observation.wind_kph;
var wind_string = wind_direction + " " + wind_speed + " Km/h";
alert("Weather: " + weather + "\n"
+ "Temp: " + temp + "\n"
+ "Humidity: " + humid + "\n"
+ "Wind: " + wind_string + "\n"
+ lastUpdated
);
}
});
});
</script>

Categories

Resources