If variable is empty, don't display display associated HTML - javascript

I am working on a PhoneGap iOS Facebook app and I am working on showing the user's newsfeed. Here is my code so far:
<script>
function showPosts() {
FB.api('/me/home', function(response) {
console.log(response);
if (!response.error) {
var markup = '';
var messages = response.data;
for (var i = 0; i < messages.length && i < 5; i++) {
var message = messages[i];
markup += '<p><img src="' + message.picture + '">' + message.message + '<img src="https://graph.facebook.com/' + message.from['id'] + '/picture">' + message.from['name'] + '</p><br>';
}
document.getElementById('newsfeedposts').innerHTML = markup;
}
});
}
</script>
Right now, if there is no message in a post, "undefined" is displayed. Also, when there is no message picture, there is an empty image icon, because the <img> tag is still being loaded. Would it be possible to create an if statement saying if message.picture is empty than don't display <img src="message.picture">?
The same goes for the post message. If message.message is empty, could I create an if statement saying don't display anything if there is no message, eliminating "undefined"?
If an if statement will work, where should I place it? I tried placing an if statement in "markup" but I couldn't get it to work.

Pretty simple:
if (typeof message.picture != 'undefined') {
// message.picture is not empty, so do the stuff inside of here.
}

Since message will always exist, and picture is inside message, even if picture is undefined it would not throw an error. Therefore you can do this:
if (message.picture) {
//Do things here.
}

Related

display alert message after redirect

I have a button that executes a function:
$("#btnRemove").click(function () {
var name= $("#editAccountName").val();
if (confirm("Are you sure you want to mark " + "''" + name + "''" + " as innactive?")) {
saveAccount(false);
window.location.href = "/RxCard/Search";
}
alert (name + "was marked innactive.")
});
I need the alert to show after the user is redirected to "/Rxcard/Search"
what do i need to change in my code to get it working like that?
on a side note, how would do the same but with a CSS customized alert?
Thanks.
Instead of putting your alert in this code, you need to put it into the script behind Search page. Now you can add a url parameter and then in there check it and show the alert if that parameter is set:
if (confirm("Are you sure you want to mark " + "''" + name + "''" + " as innactive?")) {
saveAccount(false);
window.location.href = "/RxCard/Search?name=" + name;
}
And then add this somewhere (doesn't matter that much):
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
And at last this code goes into your search page code:
function() {
if($.urlParam('name') == true){
alert (name + "was marked innactive.");
}
}();
You cannot run an alert after the location.href has changed because it causes the browser to refresh. Once refreshed, your script is no longer running.
You would need to move your alert script into your search page and perhaps pass the name as a querystring arguement.
You could store the name value using localstorage. The value can be evaluated after the redirection so you can display the dialog with the stored value (if any)
You can't style your alert dialog but you can always create a modal dialog from scratch or by using a web framework / library.

Why does the Flickr public feed API return "undefined" before displaying photo results when accessed by jQuery?

I started working with APIs/Ajax/JSON recently and began a small project to test my knowledge.
I made a simply website where you type a word into a form and it brings back Flickr photos associated with the word.
It works pretty well, but it always includes a simple "undefined" before the first photo which messes with the display of the first row of pictures.
An example can be seen here, simply search for a photo tag and you'll see what I'm talking about:
http://codepen.io/anon/pen/jPExNm
Here is the related jQuery:
$('form').submit(function (evt) {
evt.preventDefault();
// the AJAX part
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var query = $('#photoQuery').val();
var flickrOptions = {
tags: query,
format: "json"
};
function displayPhotos(data) {
var photoHTML;
$.each(data.items,function(i,photo) {
photoHTML += '<div class="photo">';
photoHTML += '<a href="' + photo.link + '" class="image">';
photoHTML += '<img src="' + photo.media.m + '"></a></div>';
}); // end each
$('#photoGallery').html(photoHTML);
}
$.getJSON(flickerAPI, flickrOptions, displayPhotos);
}); // end submit
I haven't found any errors related to this in the Javascript console and couldn't find anything like this while Googling, so I'm turning to StackOverflow. Thank you for any and all help.
Because
var photoHTML;
is the same thing as
var photoHTML = undefined;
Basic example of what you are doing
var str;
str = str + "123"; // undefined + "123" = "undefined123";
You need to set it to an empty string
var photoHTML = "";

Using HTML Tags in Wordpress Page. Getting Error: "Unexncaught SyntaxError..."

I am retrieving data from Parse in my Wordpress page fine. I can append the names of my objects into a page in Wordpress, but as soon as a try to append a HTML tag like <h1> or <p>, I get an error within my Chrome console:
Uncaught SyntaxError: Unexpected token ILLEGAL
Below is the code within my wordpress page that works without errors:
<div id="list1"><h1>Beer List</h1></div>
<div id="list2"><h1>Tap List</h1></div>
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
Parse.initialize("", "");
var Objs = Parse.Object.extend("Obj");
var query = new Parse.Query(Objs);
query.ascending("name");
query.find({
success: function(results) {
var obj1String = '';
var obj2String = '';
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' '+object.get('name')+'</br>';
if(object.get('isObj2') == true){
obj2String = obj2String +' '+object.get('name')+'</br>';
}
}
jQuery( "#list1" ).append( obj1String );
jQuery( "#list2" ).append( obj2String );
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
</script>
But when I add, for example a tag to one of my objStrings, I get the error. i.e.:
obj1String= obj1String +'<h1>'+object.get('name')+'</h1></br>';
Here is how the page is rendering, any why the error is happening. It seems to be adding a line break when it sees those tags:
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' //line break added here
<h1>'+object.get('name')+'</h1>
<p></br>';
if(object.get('isObj2') == true){
objString = obj2String +' '+object.get('name')+'</br>';
}
I have see other threads for this error (i.e. here). But I could not get any suggestions there to work.
Any help would be greatly appreciated, thanks!
I've had a similar problem to this before and I fixed it by making sure all the HTML tags in the JavaScript are on the same line.
As for wordpress template files you can read more about it here http://codex.wordpress.org/Page_Templates. Simply it will allow you to use a PHP file as a template to display that page.

how do I remove an item that is set to upload?

I have created an uploader using javascript and php. The problem is that I only want to allow specific file types. I have it letting the user know the file is not valid but I am not sure how to remove the file from being uploaded. Can anyone tell me how to remove the upload?
multiUploader.prototype._preview = function(data) {
this.items = data;
if (this.items.length > 0) {
var html = "";
var uId = "";
for (var i = 0; i < this.items.length; i++) {
uId = this.items[i].name._unique();
if (typeof this.items[i] != undefined) {
if (self._validate(this.items[i].type) <= 0) {
var errorClass = '<h3 class="text-danger">Invalid file format' + this.items[i].name + '</h3>'
jQuery(".errorContent").append(errorClass);
jQuery.remove(this.items[i]);
}
html += '<div class="dfiles" rel="' + uId + '"><h5>' + this.items[i].name + '</h5><div id="' + uId + '" class="progress" style="display:none;"></div></div>';
}
}
jQuery("#dragAndDropFiles").append(html);
}
}
This is not all of the code, just the function that displays my error message and also shows the uploaded file on the page. I tried it with jQuery.remove but it does not work. Any ideas are appreciated
what is a "file type"? I could send you a .php file that ends in .jpg, would you accept that? (I hope not!). Let the user upload the files with a warning that files X, Y, Z are not going to be accepted based on extension mismatch. Then actually test their content to see if the files are truly what their extension claims, because -and this part is important- your javascript in no way guarantees that what you're going to get is what you wrote your scripts to allow. Changing your script in my browser is a matter of opening my devtools and rewriting your script, then hitting ctrl-s. Now my browser will be running my code, not your code, and happily upload my files anyway.
Always, always, server-verify the user data.

Not able to append data to Div and redirect page

I have a default page with list of items. When I click on those Items I need to dynamically append data to div in Page B and redirect the app to Page B.
I added this div in PageB
''
On Click event I am doing following action in .js file:
'$(document).on('click', '#selectConcept', function (node) {
var ncid = this.textContent.slice(6,25);
$.ajax({
dataType: "json",
url: "http://txv-trmindexer01:8080/CommonTerminologyLeopardSearch/rest/getConceptByNcid/" + ncid,
error: function () {
alert("ERROR");
},
success: function (data) {
window.location.href = 'getfacets.html';
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
} });
});'
I am able to redirect page, but nothing is appended to Div.
Can anyone help me out with this..
I'm not really sure, but I guess the code runs before the new page is loaded. So you could try to wrap the code in a function run at onload event time
window.location.href = 'getfacets.html';
window.onload = function() {
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
}
The problem:
As soon as you set "window.location.href" property the page navigates to your page B and you loose your fetched data.
You have two solutions to the problem:
Use Single Page Application (SPA) application approach wherein you could create a new global scope for your fetched data, which can now be used by page B
Send the ncID as a querystring parameter to page B and and implement the service call and data appending logic on page B

Categories

Resources