Unexpected token while using jquery on event - javascript

I'm trying to bind on to a click event for a class but continue to get this error:
Uncaught SyntaxError: Unexpected token ;
My jquery and HTML
function loadData() {
isLoading = true;
$('#loaderCircle').show();
$.post(apiURL, { f: 'gridview', start: pgStart, end: pgEnd, params: $("#search_basic_form_id").serialize() }, function(data){
if (data.success) {
// Create HTML for the images.
var html = '';
$.each(data.profiles, function() {
html += '<li><div class="image-wrapper">';
html += '<div class="image-options">';
html += '<br>Favorite';
html += '</div>';
html += '<a href="/view_profile.php?id='+this.user_id+'">';
html += '<img src="'+this.file_name+'" width=200px; height="'+this.height+'px" style="border:0;">';
html += '</a>';
// Image title.
html += '<p>'+this.name+' '+this.age+'</p>';
html += '<p>'+this.city+', '+this.state+'</p>';
html += '</div>';
html += '</li>';
});
// Add image HTML to the page.
$('#tiles').append(html);
// Apply layout.
applyLayout();
pgStart = data.start;
pgEnd = data.end;
}
}, "json");
};
$(document).ready(function() {
// Load first data from the API.
loadData();
$('.favoriteButton').on('click', function(e) {
e.preventDefault();
alert("Favorite Clicked");
});
...
Not sure why I'm getting this error but it points to the last semi colon in the jquery call.

Ah, figured it out I think. Try this for your document ready:
$(document).ready(function() {
Difference is the lack of new.

Related

How to display json data from js file in html page inside div

Here,I am getting data from db in JSON format into my .js file and I am getting in div also .But I am not getting the div in my HTML page.Please can anyone tell me how to show in my HTML page.Below is my code:
My json array:
[{"chat_question_id":"1",
"chat_question_title":"What is PHP?"},
{"chat_question_id":"17",
"chat_question_title":"what is php?",}
Below is my js code:
function ChatQuestionsInfo(bRowId)
{
var actionType = "";
var hdnFlagForSearchQue = $("#hdnFlagForSearchQue").val();
if(hdnFlagForSearchQue=="insert"){
actionType = "ChatQuestionsInfo";
} else {
actionType = "searchQuestiontitle";
}
if($.trim($("#questionname").val())==""){
$("#questionname").focus();
alert("Enter Question Name");
return false;
}
if($.trim($("#technologytags").val())==""){
$("#technologytags").focus();
return false;
}
$.post(rootUrl+"includes/ajax/ajax_chat.php", {action: actionType,bRowId:bRowId,bQuestionName: $.trim($("#questionname").val()),bTechnologyTags: $.trim($("#technologytags").val())},
function(data){
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="tab-content">';
htmlText += '<div id="newquestions"> : ' + data[key].chat_question_title + '</div>';
htmlText += '</div>';
}
$('.chat_body_form').append(htmlText);
}, "json");
return false;
}
HTML code:
<div id="newquestions"></div>
I think you need to make 2 changes, 1 is in ajax_chat.php file. and second in your javascript.
Every JSON output need to have in pure JSON output, so javascript (or jquery) can easily read it. so on output of ajax_chat.php file, you have to set a header to give proper output content type.
for example
header('Content-Type:application/json');
echo json_encode('your varialbe array');
In jquery it is better to use $.each then for loop, and also you can append the data directly in the loop.
for example
function(data){
$.each(data,function(i){
$('.chat_body_form').append('<div class="tab-content"><div id="newquestions"> : '+ $(this).chat_question_title + '</div></div>';
});
}
I think these changes will work and also will be very simple and clean code to understand or change,
Thanks...

Function within function in JavaScript - Need to understand this code:

I have below code within a function called render. How do I call the str variable value outside render function?
Also, please can you explain below code? I'm fairly new to js and head is hurting looking at the function calls having functions as a parameter.
My understanding is that app.getList is an object which takes function as a parameter? but it is not returning anything. Sorry, I'm lost here.
app.getList("FieldList", function(reply){
var str = "";
$.each(reply.qFieldList.qItems, function(index, value) {
str += value.qName + ' ';
});
console.log(str);
});
Full Code:
define(["jquery",
//mashup and extension interface
"qlik",
//add stylesheet
"text!./css/mystyle.css",
"client.utils/state",
"client.utils/routing"
],
function($, qlik, cssContent, clientState, clientRedirect) {
/*-----------------------------------------------------------------*/
// function redirect (sheetId){
// clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state])
// }
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
var render = function($elem, layout) {
var html = '',
app = qlik.currApp();
//get list of tab objects and insert into div
app.getAppObjectList('sheet', function(arrayitem) {
//for each sheet in the app, create a list item
$.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) {
//include the sheet id as the list item id to be used as a reference for active sheet
html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + ');
//wrap anchor tag to be used by bootstrap styling
html += '<a>';
//give the link the same name as the sheet
html += myvalue.qData.title;
html += '</a>';
html += '</li>';
});
html += '</ul></div>';
html += "<button id='myButton'> Click Me!! </button>";
console.log(arrayitem.qAppObjectList);
console.log(html);
//insert html into the extension object
return $elem.html(html);
});
/* Test Code Start from here */
app.getList("FieldList", function(reply) {
var str = "";
$.each(reply.qFieldList.qItems, function(key, value) {
str += value.qName + ' ';
});
console.log(str);
});
};
/*-----------------------------------------------------------------*/
return {
/*-----------------------------------------------------------------*/
paint: function($element, layout) {
console.count();
/*-----------------------------------------------------------------*/
$(function() {
$element.html("#myButton").click(function() {
// for(var mynum = 1; mynum <= 5; mynum++){
// alert('button test' + mynum);
// };
});
});
/*-----------------------------------------------------------------*/
render($element, layout);
/*-----------------------------------------------------------------*/
}
};
});
app.getList is probably asynchronous (meaning it runs in the background). The function you've passed to it is a callback. That function will be ran at some point in the future, once the AJAX call (or whatever asynchronous method is ran) is done.
Your callback is passed reply, which is the "return" value from getList(). You cannot access str from outside of this function. You need to do whatever code with reply and/or str in that function only.

dynamically generated elements not displaying on the screen

I create some dynamically generated html by jQuery and then add some click event on this generated html.
The click event work fine and the code inside run correctly and add some anther dynamically generated html to the first dynamically generated html on the page.
So what I am trying to do is first dynamically generated html then add click event on it after the click event is triggered, add some more dynamically generated html to the fist dynamically generated html.
This all works fine but the second dynamically generated html not displaying on the screen, I inspect element on the target html and the html was generated but still not displayed on the screen.
Here is my code :
$(function () {
console.log("Category Page Script loaded");
$.post('/Category/GetCategories', {}).success(function (data) {
console.log(data);
$Category = $('ul#Category-filter');
$Category.empty();
console.log("coustom empty");
var html = '';
for (sub in data) {
console.log(data[sub].CategoryID, data[sub].CategoryName);
var html = '<li class="dropdown-tree CategorySelected" data-id="' + data[sub].CategoryID + '">'
+ '<a class="dropdown-tree-a">' + data[sub].CategoryName + ' COLLECTION </a>'
+ '<ul class="category-level-2 dropdown-menu-tree" id="category">'
+ '</ul>'
+ '</li>'
console.log(html);
$Category.append(html);
}
}).error(function () {
console.log('error');
});
//___________________________________________________________________________
$(document).on('click', 'li.CategorySelected', function () {
console.log("clickd");
// Get the id from the link
var SelectedCategoryID = $(this).attr("data-id");
console.log(SelectedCategoryID);
if (SelectedCategoryID != '') {
console.log('1');
$CategorySelected = $('#category');
console.log($CategorySelected);
console.log('2');
$CategorySelected.empty();
console.log('3');
console.log("CategorySelected empty");
console.log('4');
var html = '';
console.log('5');
$.post("/SubCategory/GetSubCategories", { SelectedCategoryID: SelectedCategoryID },
function (data) {
console.log(data);
console.log('6');
for (sub in data) {
console.log(data[sub].SubCategoryID, data[sub].SubCategoryName);
var html = '<li>' + data[sub].SubCategoryName + ' </li>'
console.log(html);
$CategorySelected.append(html);
console.log($CategorySelected);
}
});
}
});
//_________________________________________________________
});
This problem occurs only when parent element id is duplicate, please ensure that no dulipcate id is used for parent element.

'no image' icon while outputting AJAX-delivered content [duplicate]

This question already has answers here:
How to show Page Loading div until the page has finished loading?
(13 answers)
Closed 8 years ago.
I use AJAX requests to retrieve data from mySQL (link), after that I build a sequence of post. Every post has a feature image. So while in process of outputting the posts, the visitor sees 'no image' sign:
.
This lasts for a bit of second, but looks bad.
How can I prevent this sign from showing, or subtitute with a loading spin?
jQuery part for outputting the results
function postsBuilder(posts){
var contents ='';
$.each(posts, function(k, field){
if(field.link[field.link.length-1] == '/') {field.link = field.link.slice(0, field.link.length-1)};
contents += '<div class="post-container">';
//here I output the feature image
contents += "<div class='col_1'><div class='post_image'><img src='/images/icons/id_" + field.id + ".png'></div></div>";
contents += "<div class='col_2'><div class='post_name'><a class='post_name_link' target='blank' href=http://" + field.link + ">" + field.name + "</a></div>";
contents += "<div class='post_link'>" + field.link + "</div>";
contents += "<div class='post_content'>Content: " + field.content + "</div>";
if ( field.video.indexOf('you') >-1 ) {contents += "<div class='post_video'><a data-toggle='lightbox' href=" + field.video + ">Video</a></div>";}
contents += "</div></div><br />";
});
return contents;
}
One of examples when the function is called
$.ajax({cache:false,
url:str,
beforeSend: function() { $('#loadingDiv').show(); },
complete: function() { $('#loadingDiv').hide(); },
dataType :'json'})
.done(function(result){
var i, j, m=0;
var div_content="";
div_content += "<div><b>Category: ".concat(result[0].category).concat("</b></div>");
posts_array = [];
for (i=0,j=result.length; i<j; i+=size) { // slice whole JSON result into portions of at maximum 'size' posts in each
posts_array.push(result.slice(i, i+size));
m++;
}
div_content += postsBuilder(posts_array[0]);
...
$("#content").html(div_content);
});
Use the error event for images:
$(document).on('error', 'img', function () {
$(this).hide();
// or $(this).css({visibility:"hidden"});
});
Check out How to silently hide "Image not found" icon when src source image is not found

Limit number of Dynamic list Items in a Function

I would like to achieve 2 things with this Code I have been working on so not sure if to separate the Questions:
JS:
function listPosts(data) {
postlimit =
var output='<ul data-role="listview" data-filter="true">';
$.each(data.posts,function(key,val) {
output += '<li>';
output += '<a href="#devotionpost" onclick="showPost(' + val.id + ')">';
output += '<h3>' + val.title + '</h3>';
output += '<p>' + excerpt + '</p>';
output += '</a>';
output += '</li>';
}); // go through each post
output+='</ul>';
$('#postlist').html(output);
} // lists all the posts
Questions:
1: I would like to limit the number of Dynamic List Posts returned to 8
2: While I limit the displayed items, I want to add a 'More...' text at the bottom so another set of 8 items is appended to already displayed list.
I am already trying out some codes but was hoping to get some guidance
function listPosts(data, postlimit) {
var $output = $('<ul class="posts" data-role="listview" data-filter="true">');
$.each(data.posts,function(key, val) {
$("<li>", {id: "post_" + val.id})
.append([
$("<h3>", {text: val.title}),
$("<p>", {text: val.excerpt})
])
.appendTo($output);
return (postlimit-- > 1);
});
$('#postlist').empty().append($output);
}
// exemplary delegated event handler
$(document).on("click", "ul.posts h3", function () {
$(this).show();
});
later ...
listPosts(data, 8);
Notes:
from $.each() you can return true or false. If you return false, the loop stops.
Try not to build HTML from concatenated strings. This is prone to XSS vulnerabilities that are easy to avoid. jQuery gives you the tools to build HTML safely.
Generally, for the same reason, try to avoid working with .html(), especially if you already have DOM elements to work with.
Don't use inline event handlers like onclick. At all. Ever.
I am answering you on basis of pure logic and implementation of logic. there could be API stuff for it , but I don't really know. Secondly; It would be a good solution to find some jQuery plugin if you don't have any problems with using jQuery.
call the function onMoreClick() upon clicking the More... html item
var end = 8;
var start = 1;
function onMoreClick()
{
start = end
end = end+8;
listPosts(data)
}
function listPosts(data) {
postlimit =
var output='<ul data-role="listview" data-filter="true">';
var i = start;
$.each(data.posts,function(key,val) {
if(i<end && i >=start){
output += '<li>';
output += '<a href="#devotionpost" onclick="showPost(' + val.id + ')">';
output += '<h3>' + val.title + '</h3>';
output += '<p>' + excerpt + '</p>';
output += '</a>';
output += '</li>';
i++;
}
}); // go through each post
output+='</ul>';
$('#postlist').html(output);
} // lists all the posts

Categories

Resources