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>
Related
What I'm trying to achieve is a Zapier Code (JS) action to preform a Twitter reply to a given status ID with a given text .
I'm already using the functioning Zapier (JS) Code action offered by #KayCee which preform a POST favorites/create and would like to modify it so it would preform a reply action to any given status_id using the POST statuses/update (in_reply_to_status_id) as instructed by Twitter API.
Here is #KayCee's code with the modifications I made to preform a reply:
// This code requires that you set the ID of the tweet that you want to reply to as an input variable called "reply_to_id" and the text you wish to reply as an input variable called "status_text". Learn more at https://zapier.com/help/code/#data-variables
// INSTUCTIONS FOR SETTING THESE REQUIRED VARIABLES: After you create a new app at https://apps.twitter.com/, click on the name of the app to open it. Then, select the "Keys and Access Tokens" tab.
var twitterApplicationConsumerKey = 'CONSUMERKEY';
var twitterApplicationConsumerSecret = 'CONSUMERSECRET';
var twitterApplicationAccessToken = 'ACCESSTOKEN';
var twitterApplicationAccessTokenSecret = 'ACCESSTOKENSECRET';
// That's it. No need to edit anything below.
function b64_hmac_sha1(k,d,_p,_z){
if(!_p){_p='=';}if(!_z){_z=8;}function _f(t,b,c,d){if(t<20){return(b&c)|((~b)&d);}if(t<40){return b^c^d;}if(t<60){return(b&c)|(b&d)|(c&d);}return b^c^d;}function _k(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}function _s(x,y){var l=(x&0xFFFF)+(y&0xFFFF),m=(x>>16)+(y>>16)+(l>>16);return(m<<16)|(l&0xFFFF);}function _r(n,c){return(n<<c)|(n>>>(32-c));}function _c(x,l){x[l>>5]|=0x80<<(24-l%32);x[((l+64>>9)<<4)+15]=l;var w=[80],a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(var i=0;i<x.length;i+=16){var o=a,p=b,q=c,r=d,s=e;for(var j=0;j<80;j++){if(j<16){w[j]=x[i+j];}else{w[j]=_r(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);}var t=_s(_s(_r(a,5),_f(j,b,c,d)),_s(_s(e,w[j]),_k(j)));e=d;d=c;c=_r(b,30);b=a;a=t;}a=_s(a,o);b=_s(b,p);c=_s(c,q);d=_s(d,r);e=_s(e,s);}return[a,b,c,d,e];}function _b(s){var b=[],m=(1<<_z)-1;for(var i=0;i<s.length*_z;i+=_z){b[i>>5]|=(s.charCodeAt(i/8)&m)<<(32-_z-i%32);}return b;}function _h(k,d){var b=_b(k);if(b.length>16){b=_c(b,k.length*_z);}var p=[16],o=[16];for(var i=0;i<16;i++){p[i]=b[i]^0x36363636;o[i]=b[i]^0x5C5C5C5C;}var h=_c(p.concat(_b(d)),512+d.length*_z);return _c(o.concat(h),512+160);}function _n(b){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s='';for(var i=0;i<b.length*4;i+=3){var r=(((b[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((b[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((b[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>b.length*32){s+=_p;}else{s+=t.charAt((r>>6*(3-j))&0x3F);}}}return s;}function _x(k,d){return _n(_h(k,d));}return _x(k,d);
}
var replyToId = input.reply_to_id;
var status = input.status_text;
//create nonce
function generateRandomString(desiredLengthOfRandomString) {
var result = '';
var possibleCharactersForRandomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < desiredLengthOfRandomString; i++ )
result += possibleCharactersForRandomString.charAt(Math.floor(Math.random() * possibleCharactersForRandomString.length));
return result;
}
var randomString = generateRandomString(32);
var nonce = new Buffer(randomString).toString('base64');
//create timestamp
var timestamp = Math.floor(new Date() / 1000);
//create the signature
var signatureParameterString = 'in_reply_to_status_id=' + replyToId + '&status=' + status + '&oauth_consumer_key=' + twitterApplicationConsumerKey + '&oauth_nonce=' + encodeURIComponent(nonce) + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + timestamp + '&oauth_token=' + twitterApplicationAccessToken + '&oauth_version=1.0';
var signatureBaseString = 'POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json&' + encodeURIComponent(signatureParameterString);
var signingKey = encodeURIComponent(twitterApplicationConsumerSecret) + '&' + encodeURIComponent(twitterApplicationAccessTokenSecret);
var signature = b64_hmac_sha1(signingKey, signatureBaseString);
var apiUrl = 'https://api.twitter.com/1.1/statuses/update.json?in_reply_to_status_id=' + replyToId + '&status=' + status;
var oauthString = 'OAuth oauth_consumer_key="' + twitterApplicationConsumerKey + '", oauth_nonce="' + encodeURIComponent(nonce) + '", oauth_signature="' + encodeURIComponent(signature) + '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' + timestamp + '", oauth_token="' + twitterApplicationAccessToken + '", oauth_version="1.0"';
fetch(apiUrl, {
method: 'POST',
headers: {
'Authorization': oauthString
}
})
.then(function(res) {
return res.json();
})
.then(function(body) {
var output = body;
callback(null, output);
})
.catch(callback);
For some reason, I keep on getting error message: "Could not authenticate you" although the same code worked for performing a "like".
Not sure what am I doing wrong?
I have recently came across this JS code for Zapier by #ReganStarr to create a "like tweet" action for any given tweet_id. I'm no expert but it sure looks fine (no error messages either), nevertheless, for some reason it doesn't work!
Would appreciate a lot if an experienced Zapier + JS eye can identify why isn't it working.
here is the code:
var twitterApplicationConsumerKey = 'MyTwitterConsumerKey';
var twitterApplicationConsumerSecret = 'MyTwitterConsumerSecret';
var twitterApplicationAccessToken = 'MyTwitterAccessToken';
var twitterApplicationAccessTokenSecret = 'MyTwitterTokenSecret';
// That's it. No need to edit anything below.
function b64_hmac_sha1(k,d,_p,_z){
if(!_p){_p='=';}if(!_z){_z=8;}function _f(t,b,c,d){if(t<20){return(b&c)|((~b)&d);}if(t<40){return b^c^d;}if(t<60){return(b&c)|(b&d)|(c&d);}return b^c^d;}function _k(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}function _s(x,y){var l=(x&0xFFFF)+(y&0xFFFF),m=(x>>16)+(y>>16)+(l>>16);return(m<<16)|(l&0xFFFF);}function _r(n,c){return(n<<c)|(n>>>(32-c));}function _c(x,l){x[l>>5]|=0x80<<(24-l%32);x[((l+64>>9)<<4)+15]=l;var w=[80],a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(var i=0;i<x.length;i+=16){var o=a,p=b,q=c,r=d,s=e;for(var j=0;j<80;j++){if(j<16){w[j]=x[i+j];}else{w[j]=_r(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);}var t=_s(_s(_r(a,5),_f(j,b,c,d)),_s(_s(e,w[j]),_k(j)));e=d;d=c;c=_r(b,30);b=a;a=t;}a=_s(a,o);b=_s(b,p);c=_s(c,q);d=_s(d,r);e=_s(e,s);}return[a,b,c,d,e];}function _b(s){var b=[],m=(1<<_z)-1;for(var i=0;i<s.length*_z;i+=_z){b[i>>5]|=(s.charCodeAt(i/8)&m)<<(32-_z-i%32);}return b;}function _h(k,d){var b=_b(k);if(b.length>16){b=_c(b,k.length*_z);}var p=[16],o=[16];for(var i=0;i<16;i++){p[i]=b[i]^0x36363636;o[i]=b[i]^0x5C5C5C5C;}var h=_c(p.concat(_b(d)),512+d.length*_z);return _c(o.concat(h),512+160);}function _n(b){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s='';for(var i=0;i<b.length*4;i+=3){var r=(((b[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((b[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((b[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>b.length*32){s+=_p;}else{s+=t.charAt((r>>6*(3-j))&0x3F);}}}return s;}function _x(k,d){return _n(_h(k,d));}return _x(k,d);
}
var tweetId = input.tweet_id;
//create nonce
function generateRandomString(desiredLengthOfRandomString) {
var result = '';
var possibleCharactersForRandomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < desiredLengthOfRandomString; i++ )
result += possibleCharactersForRandomString.charAt(Math.floor(Math.random() * possibleCharactersForRandomString.length));
return result;
}
var randomString = generateRandomString(32);
var nonce = new Buffer(randomString).toString('base64');
//create timestamp
var timestamp = Math.floor(new Date() / 1000);
//create the signature
var signatureParameterString = 'id=' + tweetId + '&oauth_consumer_key=' + twitterApplicationConsumerKey + '&oauth_nonce=' + encodeURIComponent(nonce) + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + timestamp + '&oauth_token=' + twitterApplicationAccessToken + '&oauth_version=1.0';
var signatureBaseString = 'POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Ffavorites%2Fcreate.json&' + encodeURIComponent(signatureParameterString);
var signingKey = encodeURIComponent(twitterApplicationConsumerSecret) + '&' + encodeURIComponent(twitterApplicationAccessTokenSecret);
var signature = b64_hmac_sha1(signingKey, signatureBaseString);
var apiUrl = 'https://api.twitter.com/1.1/favorites/create.json?id=' + tweetId;
var oauthString = 'OAuth oauth_consumer_key="' + twitterApplicationConsumerKey + '", oauth_nonce="' + encodeURIComponent(nonce) + '", oauth_signature="' + encodeURIComponent(signature) + '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' + timestamp + '", oauth_token="' + twitterApplicationAccessToken + '", oauth_version="1.0"';
fetch(apiUrl, {
method: 'POST',
headers: {
'Authorization': oauthString
}
})
.then(function(res) {
return res.json();
})
.then(function(body) {
var output = body;
callback(null, output);
})
.catch(callback);
Thanks :-)
I just tried the code you posted and it worked for me.
You might double-check that you have your Access Levels set to "read and write" for your app at https://apps.twitter.com/ so that the 4 variables you include at the top of your code have the correct permissions.
And also make sure that you pass in tweet_id in the Input Data of the Zapier code step. (screenshot)
hey i am making a simple web form its a product detail insertion web page. I am trying to insert using ajax call. without ajax it works .. but $.ajax is not invoking my code behind static method, no idea wat's the issue. here's the code:
$(document).ready(function () {
$("#submit").click(function () {
var cat = document.getElementById('DropDownList1').value;
var nm = document.getElementById('name').value;
var cde = document.getElementById('code').value;
var dt = document.getElementById('dt').value;
var price = document.getElementById('price').value;
var f3 = document.getElementById('ty').innerHTML;
alert("you clicked " + cat + " - " + nm + "-" + cde + "-" + dt +
"-" + price + "-" + f3 + "-");
//////////////uptil here alert gives the right value.
$.ajax({
method: "POST",
contentType: "application/json",
url: "home.aspx/ins",
dataType: "json",
data: "{'Name :' + nm + 'code :' + cde +'category :'+ cat +
'date :'+ dt +'price :'+ pr +'img_name :' + f3}",
//data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
//////////////////////////////// here is the code behind method:
[System.Web.Services.WebMethod]
public static void ins(string Name,string code,string category, DateTime date,
int price,string img_name)
{
productclass pc = new productclass();
pc.Pr_name = Name;
pc.Code = code;
pc.Category = category;
pc.Expiry = date;
pc.Price = price;
pc.Pr_image = img_name;
dalinsert di = new dalinsert();
bool flag = di.insert(pc);
}
Correct way to pass data to ajax post via webmethod is like this.
var params = "{'Name' :'" + nm + "', 'code' :'" + cde + "', 'category' :'" + cat + "', 'date' : '" + dt + ", 'price' :'" + pr + "' , 'img_name' :'" + f3 + "' }" // Declare this above $.ajax...
data: params, //Use above in $.ajax... .
I believe the issue is in your data being passed in:
data: "{'Name :' + nm + 'code :' + cde +'category :'+ cat +'date :'+ dt +'price :'+ pr +'img_name :' + f3}"
I see two possible issues there. First, your '+' are being treated as literals there as they are surrounded by double quotes that are never escaped. What you are trying to achieve, I believe, is:
data: "{'Name :'"+ nm +"'code :'"+ cde +"'category :'"+ cat +"'date :'"+ dt +"'price :'"+ pr +"'img_name :'"+ f3 +"}"
However that still has a potential problem as I believe that json will be malformed. The expected syntax of a json string, with string variables at least, is '{"key1":"value1","key2":"value2"}'.
A better way to make sure your right and to save yourself work is to use JSON.stringify to do the work for you.
var temp = {};
temp.Name = nm;
temp.code = cde;
temp.category = cat;
temp.date = dt;
temp.price = pr;
temp.img_name = f3;
var data = JSON.stringify(temp);
I've written some scripts to convert the pagination (20 photos per ajax request) from instagram json feeds to csv for easily storing the photo urls in our database. Our CMS is automatically able to convert CSV files into SQl files either by replacing the table or by appending to it. The problem is it will only work if ALL of the columns are the same.
It's close to totally working but I can't import my generated csvs because they keep getting an empty column where it should be line breaking to a new row because the final CSV output contains a comma + line break when it should only be returning the line break (i.e. without a trailing comma).
Encoding is UTF-8 and line breaks are being added using "\n". I've tried console logging just about every step of the process and it seems that there that
Here's a picture of one of the CSVs I am generating: http://screencast.com/t/dZfqN08A
Below is all the relevant code:
First I'm using ajax with a jsonp callback to load instagram photos based on a hashtag.
Photos are loaded like this:
function loadNext(nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
console.log('loadmore');
if (object) {
console.log(object);
$('.loadmore').fadeOut(500);
// chargement photos gallerie
$.each( object.data, function(home, photo) {
photo = '<div class="photo photo-load">' +
'<img class="pull-me" src="' + photo.images.low_resolution.url + '" height="380px" width="380px" alt="photo">' +
'<div class="dot"></div>' +
'<div class="share" >' +
'<!-- AddThis Button BEGIN -->' +
'<div class="addthis_toolbox addthis_default_style addthis_16x16_style">' +
'<a class="addthis_button_twitter"></a>' +
'<a class="addthis_button_facebook"></a>' +
'</div>' +
'<!-- AddThis Button END -->' +
'</div>' +
'<div class="text-photo">' +
'<div class="svg line w-line"></div>' +
'<h4 class="left">'+ photo.user.username + '</h4>' +
'<h4 class="right share-photo">PARTAGE</h4>' +
'</div>' +
'<div class="vote w-path-hover">' +
'<div class="fb-like" data-href="http://dev.kngfu.com/maurice/" data-layout="box_count" data-action="like" data-show-faces="false" data-share="false"></div>' +
'<div class="insta-like">' +
'<div class="count-box">' +
'<p>'+ photo.likes.count + '</p>' +
'</div>' +
'<a class="insta-button" title="Pour appuyer votre proposition préférée, rendez-vous sur Instagram." href="http://instagram.com/" ><i class="fa fa-instagram"></i>J aime</a>' +
'</div> ' +
'<div class="w-path"></div>' +
'<div class="base-cross"></div>' +
'<h4 class="vote-button">VOTE</h4>' +
'</div>' +
'</div>';
$(photo).appendTo( $( ".gallery" ) );
});
url = object.pagination.next_url;
console.log(url);
} else {
console.log("error");
}
} // end success func.
});
}
Then in a separate ajax call I can convert the same json feed to a csv file using this function (this function also calls a couple other functions so the dependent functions are included below the ajax call):
function convertJSON (nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
if (object) {
console.log(object);
var fromJSON = new Array();
i = 0;
$.each( object.data, function(home, photo) {
i++;
var photopath = photo.images.low_resolution.url;
var postID = photo.id;
var userID = photo.user.id;
var user = photo.user.username;
// watch out for those wild fullnames in instagram json
var fullname = photo.user.full_name;
fullname = fullname.replace(/[^a-z0-9]+|\s+/gmi, " ");
//console.log(fullname);
var likes = photo.likes.count;
var winner = 0;
var winnerplace = " ";
var campaign = "maurice1";
var timestamp = photo.created_time;
// easydate field formatting
var date = new Date();
date.setSeconds( timestamp );
var photodeleted = 0;
// add new rows to csv
var linebreak = "\n";
var arrayFromJSON = new Array( linebreak+photopath,
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join();
});
//url = object.pagination.next_url;
//console.log(url);
//console.log( fromJSON );
makeCSV( fromJSON );
} else {
console.log("error");
}
} // end success func.
});
}
// json to csv converter
function makeCSV (JSONData) {
//console.log("makeCSV() function was started");
var data = encodeURIComponent(JSONData);
var currentTime = new Date().getTime();
var date = getDate( currentTime );
//console.log(JSONData);
var fileName = date;
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ data; // finally append our URI encoded data
console.log(uri);
// generate a temp <a /> tag that will auto start our download when the function is called
var link = document.createElement("a");
link.id = new Date().getTime();
link.href = uri;
// link visibility hidden
link.style = "visibility:hidden";
link.download = fileName + ".csv";
// append anchor tag and click
$("div#hidden").append(link);
link.click();
//document.body.removeChild(link);
}
// this function just makes human readable dates for CSV filename and id of our link tag
function getDate() {
var date = new Date();
//zero-pad a single zero if needed
var zp = function (val){
return (val <= 9 ? '0' + val : '' + val);
}
//zero-pad up to two zeroes if needed
var zp2 = function(val){
return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
}
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + 'h' + zp(min) + 'm' + zp(s) + 's';
}
From all the console logging I've done, I can definitely assure you that I'm getting no trailing comma until the final step where the json array data gets URI encoded.
Since this extra column is also included in the header row I'm wondering if it has to do with this line?
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
I've also tried ISO-8859-1 encoding but I get the same result.
Does anyone know why this is happening? Any help would be appreciated
Your passing an array of lines to encodeURIComponent. That will stringify the array, joining it with a comma - which you don't want.
What you should do is
var arrayFromJSON = new Array( photopath,
// remove linebreak here ^
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join(",");
// make comma explicit: ^^^
…
makeCSV( fromJSON );
…
var data = encodeURIComponent(JSONData.join("\n"));
// join the lines by a linebreak: ^^^^
…
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ "\n"
// ^^^^^^ add linebreak
+ data; // finally append our URI encoded data
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.
}