I want to use a variable in the if clause which is in jQuery template. Console log says:
Uncaught Syntax Error: Unexpected token {
Here is my code:
var isActive = true;
var isPasive = false;
var isGuest = false;
var tmp = '<script>' +
'{{each hastalar}}' +
'<a href="#" class="patientRow" data-name="${$value.M_AdiSoyadi}" data-tc="${$value.M_TcKimlikNo}" data-tahlilgunu="${$value.M_TahlilGunu}"> ${M_AdiSoyadi}' +
'{{if $value.M_HastaBulunmaDurumu == "1" && ${isActive} }}' +
'<img id="imgMember_${$value.M_TcKimlikNo}" src="images/greenmember.png" title="Hasta klinik ve DYOB kayıtlarıyla örtüşüyor." style="width:15px;height:15px;"/>' +
'{{else $value.M_HastaBulunmaDurumu == "2" }}' +
'<img id="imgMember_${M_TcKimlikNo}" src="images/bluemember.png" title="Hasta kliniğinizde mevcut fakat DYOB sisteminde sizin kliniğinizde görünmüyor. Lütfen DYOB sistmine hasta kaydını yapınız." style="width:15px;height:15px;"/>' +
'{{else $value.M_HastaBulunmaDurumu == "3"}}' +
'<img id="imgMember_${M_TcKimlikNo}" src="images/redmember.png" title="Hasta kliniğinizde mevcut değil fakat DYOB sisteminde sizin kliniğinizde görünüyor. Lütfen kan tahlili yapılan hastaların listesini kontrol ediniz." style="width:15px;height:15px;"/>' +
'{{/if}}' +
'<img id="imgResult_${$value.M_TcKimlikNo}"/>' +
'<img id="imgInfo_${$value.M_TcKimlikNo}"/>' +
'</a>' +
'{{/each}}' +
'</script>';
I use jquery.tmpl.min.js. What should I do to use the variable in if clause?
For a generic approach of replacing your variables in JavaScript strings you could you the following snippet;
var tmp = '<script>' +
... +
'<\/script>'
.replace('${isActive}', isActive)
.replace('${isPassive}', isPassive)
.replace('${isGuest}', isGuest)
For a more detailed solution on your problem, we need information about the framework and template engine which you are using.
EDIT:
I noticed that the closing script tag causes an error. YOu might want to escape the closing script tag at the like so:
<\/script>
Related
I am working on building a movie search app. It is my first time using json. I cannot figure out why my code is not working. I have it running on localhost using xampp.
On submit
$('.search-form').submit(function (evt) {
// body...
evt.preventDefault();
var $searchBar = $('#search');
var omdbApi = 'http://www.omdbapi.com/?';
var movieSearchTerm = $searchBar.val();
var searchData = {
s:movieSearchTerm,
r:json
}
Here is the callback function
function displayMovies(data) {
// for each search result
$.each(data.items,function(i,movie) {
movieHTML += '<li class="desc">';
//movie title
movieHTML += '<a href="' + movie.Title + '" class="movie-title">';
//release year
movieHTML += '<a href="' + movie.Year + '" class="movie-year">';
//poster
movieHTML += '<img src="' + movie.Poster + '" class="movie-poster"></li>';
$('#movies').html(movieHTML);
}); // end each
// movieHTML += '</li>';
}
$.getJSON(omdbApi, searchData, displayMovies);
});//end submit
r:json
You made a typo.
You haven't created a variable called json and the service expects the value of r to be json.
String literals need to be surrounded with a pair of " or '.
data.items
And the JSON returned doesn't have items, it has Search.
I want to get the HTML code of a webpage after it has been modified (similar to one that we see in inspect element tab of a browser) and I want to do it programatically (if possible using python or any other programming language). Can someone suggest how I might be able to proceed with this? I know its possible since browsers are able to do it.
As the server has no access to client window after client-side changes, you have to use client side languages.
In jquery:
var fullCode= "<html>" + $("html").html() + "</html>";
if you want also to include the Doctype:
var node = document.doctype;
var fullCode = "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>';
fullcode += "<html>" + $("html").html() + "</html>";
Thanks to this
Using JQuery you can achieve this by the following code
$(document).ready(function(){
var html = "<html>"+$('html').html()+"</html>";
});
I am accessing the following JSON data at:
http://veratech.co.nz/blog/?json=1
When I try to access the "url" property that sits within an array on line 4 of the code below, I get an undefined error. Even though it will appear in console.log (line 13) with console.log(val.attachments[0].url);.
Code below:
$.each(data.posts, function(index, val){
output += '<li>';
output += '<a href="#blogpost" onclick = showPost(' + val.id + ')">';
output += '<img src="' + val.attachments[0].url + '" alt="">';
output += '<h3>' + val.title + '</h3>';
//Here we shorten the paragraph to 60 characters.
var str = val.excerpt;
var paraInfo = str.slice(0, 60);
output += '<p>' + paraInfo + '</p>';
//Closing off the the closing html tags
output += '</a>';
output += '</li>';
console.log(val.attachments[0].url);
});//Go through each post
Advice would be greatly appreciated
I think there's something else wrong.
I downloaded the json manually, and wrote this code:
HTML:
Urls:
<ul id="foo">
</ul>
JavaScript:
function extractUrls(data) {
var $foo = $('#foo');
$.each(data.posts, function (i, p) {
$foo.append($('<li></li>').text(p.attachments[0].url));
});
}
var jsonData = { /* code omitted for brevity */ };
extractUrls(jsonData);
My output was:
Urls:
<ul id="foo">
<li>http://veratech.co.nz/blog/wp-content/uploads/2014/03/martial.jpg</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/12/grave.jpg</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/12/GTA5.jpg</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/10/miyagi.jpg</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/08/htc-box.png</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/08/scaffold1.jpg</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/07/barriera.png</li>
<li>http://veratech.co.nz/blog/wp-content/uploads/2013/06/tv.jpg</li>
</ul>
Note: You should be able to replace the var jsonData = line with:
$.get('http://veratech.co.nz/blog/', { json: 1 }, extractUrls, 'json');
Anyway; can't see what's wrong with your code? Are you sure this is the issue?
PS: I even added the following inside the $.each loop:
if (!p.attachments[0].url) {
alert(p.id + ' has undefined url!');
}
And did not see any alert...
See code running in a jsFiddle here
As I need to bring separate data from a php file, and create an HTML piece to be injected with jQuery, I've choosen Json.
I send it from my PHP main file (between script tags) like this:
$.ajax({dataType: "json", url:'course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
This sends properly editedCourseId value. And what's inside course_generator.php is:
$courseId = $_POST['co_subj_co'];
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$newCourseId = $result_co['co_id'];
$newCourseName = $result_co['co_name'];
$newCourseAbbrev = $result_co['co_abbrev'];
$newCourseTypeId = $result_co['co_fk_ct_id'];
$newCourseTypeName = $result_co['ct_name'];
$isMultisubjectValue = $result_co['co_multisubject'];
$newCourseValues = '{"newCourseId":'.$newCourseId.',"newCourseName":'.$newCourseName.',"newCourseAbbrev":'.$newCourseAbbrev.',"newCourseTypeId":'.$newCourseTypeId.',"newCourseTypeName":'.$newCourseTypeName.',"isMultisubjectValue":'.$isMultisubjectValue.'}';
I am afraid Im not receiving it properly by $courseId = $_POST['co_subj_co'];, and neither $newCourseValues are being received properly on my main PHP file as my newCourseStructure is not generating anything. Could you please identify the several errors I am sure I'm making? Thank you.
UPDATE:
After changing my PHP main file to:
$.ajax({type : 'POST', dataType: "json", url:'config/forms/course_conf/course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
And my course_generator.php file to:
$courseId = intval($_POST['co_subj_co']);
$subjectList = "";
$data ="";
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
$outArr['newCourseAbbrev'] = $result_co['co_abbrev'];
$outArr['newCourseTypeId'] = $result_co['co_fk_ct_id'];
$outArr['newCourseTypeName'] = $result_co['ct_name'];
$outArr['isMultisubjectValue'] = $result_co['co_multisubject'];
$subjectsNum=mysql_num_rows(mysql_query("SELECT * FROM co_rel_subj WHERE co_subj_co = '$courseId'"));
$outArr['subjectsNum'] = $subjectsNum;
echo json_encode($outArr);
Instead of showing the HTML piece structured, this is what $newCourseStructure results:
{"newCourseId":"243","newCourseName":"a","newCourseAbbrev":"ae","newCourseTypeId":"1","newCourseTypeName":"M\u00e1ster","isMultisubjectValue":"1","subjectList":"
Edici\u00f3n y Acabado de Imagen Digital<\/div>
","subjectsNum":1}
Your JSON string is not valid JSON because you don't use quotes around the string values. Instead of manually creating JSON, create an array or object and then json_encode() it.
You don't apper to output the JSON string. Use echo or print.
Add dataType : 'json' to your ajax request so that jQuery will parse the JSON, returning the native JavaScript object. All of the variables you use in the success function are undefined. After parsing the JSON you should use
var courseId = newCourse.newCourseId; // and so on
Your ajax request doesn't have a type and so will default to GET. add type : 'POST' if you want to use POST.
Try $_GET['co_subj_co']; instead of POST.
As long as you don't specify the method to jQuery's ajax call, it's made by GET, not POST.
I have annotated two things in the code:
$.ajax({
type : 'POST',
dataType: "json",
url:'config/forms/course_conf/course_generator.php',
data:{
co_subj_co:editedCourseId
}})
.done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow"'
+ ' data-isMultisubjectValue="' + isMultisubjectValue + '"'
+ ' data-subjectsNum="' + subjectsNum + '"'
+ ' data-id="' + courseId + '"'
+ ' id="' + courseId + '"'
+ ' data-abbrev="' + newCourseAbbrev + '"'
+ ' data-courseTypeId="' + newCourseTypeId + '"'
+ ' title="' + newCourseName + '">'
+ '<div class="contentColumn40"><span class="tableContentText">'
+ newCourseName + ' (' + newCourseTypeName + ')</span></div>'
// WHERE IS subjectList DEFINED?
+ '<div class="contentColumn40">' + subjectList
+ '</div>'
+ '<div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div class="editIcon" data-id="' + courseId + '"'
+ ' title="Editar ' + newCourseName + '"></div>'
+ '</a></div></div><div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div data-id="'+courseId+'" class="discontinueIcon" '
+ 'title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';
/*
* your HTML is generated, but you never put it in the DOM
*/
$('#idOutputWrapper').empty().html(newCourseStructure);
}
When you use subjectList from the json response, please notice that it comes with a closing </div> tag for some reason, maybe you should change that, too.
btw: Your code formatting is horrible, sorry to say so. You can compress your js before uploading it to the server, but while working on it, it NEEDS to be readable. I just edited it to fit better in the codeblock here.
Are you actually using POST, or are you firing off a GET request (your browser's developer tools should tell you this easily). You should also make sure that $courseId is an integer by $courseId = intval($_POST['co_cubj_co']);. In addition, you should add a condition for the event that the requested ID is not found.
As MueR suggests, the reason to make sure that courseID is an integer is to prevent SQL injection (unless you want people to do things like delete your entire DB at will). This, of course, assumes that courseID is something like an autoincrement int.
However, you've got a number of other problems. Your JSON is invalid since you're ostensibly writing out unquoted strings... you should just use json_encode:
$outArr = array();
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
...
echo json_encode($outArr);
Personally, I prefer to just use $_REQUEST, which concatenates both $_POST and $_GET. Makes it easier.
I am working on a website that uses infinite scroll. There is a function called is_element_in_view() that gets executed on these 3 events:
scroll
load
resize
The function does exactly what it's called, it checks to see if an element with a loading gif image is in view and if so it fires an ajax request to get content from the server.
The server sends back a json object that looks like this:
[{
"url": "\/embed\/182926\/some-slug",
"thumb": "http:\/\/cdn.site.com\/91\/26\/a62c1ad74327321dab78bb194c130da5.jpg",
"type": "video",
"is_original": false,
"is_prank_news": false,
"title": "Hello World",
"description": "\t<p>Enjoy this video!<\/p>",
"teaser": "Click Me!",
"finder": "Found by <strong>Jim<\/strong> yesterday",
"likes": "2 likes",
"ad_img": null,
"media_stats": "<div class=\"media-status\">2000 views<\/div>"
},
more objects...]
There's only one object in this response for clarity sake but in reality I get back 20. This is how I'm building out the html from the json data:
$.ajax({
url: '/some/ajax/url',
type: 'get',
data: 'somedata',
dataType: 'json',
success: function(response) {
if(!$.isEmptyObject(response)) {
for(var i = 0; i < response.length; i++) {
if(response[i]) {
var item = response[i];
var title = item.title.replace(/\\"/g, '"');
var media_label = '';
var item_description_teaser = '';
var likes = '';
var ad_image = '';
var media_stats = '';
if(item.description) {
// description
item_description_teaser = '<div class="description">' + item.description.replace(/\\"/g, '"');
// teaser
item_description_teaser += (item.teaser) ? ''+ item.teaser.replace(/\\"/g, '"') +'<img src="images/teaser-arrow.png" alt="" /></div>' : '</div>';
}
// media label
if(item.type == 'article' && item.is_prank_news || item.is_original && item.is_prank_news) {
media_label = '<span class="media-label prank-news-network">Prank</span>';
}
else {
if(item.type == 'article') {
media_label = '<span class="media-label article">Article</span>';
}
else if(item.is_original) {
media_label = '<span class="media-label original">Original</span>';
}
}
// likes
if(!settings.hide_likes) {
likes = '<span class="likes">' + item.likes + '</span> | ';
}
// ad image
if(item.ad_img) {
ad_image = '<img src="'+ item.ad_img +'" alt="" class="ad-img" />';
}
block += '<article class="block">' +
'<div class="inner-left">' +
media_label +
'<a href="'+ item.url +'" title="" class="thumb">' +
'<img src="'+ item.thumb +'" alt="" width="198" height="111" />' +
'</a>' +
'</div>' +
'<div class="inner-right">' +
'<a href="'+ item.url +'" title="" class="title">' +
title +
'</a>' +
item_description_teaser.replace(/\\"/g, '"') +
'<div class="media-stats">' +
likes +
'<span class="finder">'+ item.finder.replace(/\\"/g, '"') +'</span>' +
'</div>' +
ad_image +
'</div>' +
item.media_stats +
'</article>';
}
}
$('#content').append('<div class="page page-'+ page_num +'">' + block + '</div>');
// update page count
page_num++;
// clear previous listings
block = '';
}
else {
$('#content').append('<div class="page page-1"><p class="nothing-to-show">Nothing found...</p></div>');
}
},
error: function() {
alert('error');
}
});
As you can see I put everything in one giant string stored inside the variable block. I append data to this string with every loop and append it to the page outside the loop at the end.
I feel like there is a faster way to build html from js. I read somewhere a while ago that building giant strings like I'm doing isn't as efficient as some other method the article described that I forgot. So what's the faster way to do this?
Store the blocks in an array say blocks, then
$('#content').append(blocks.join(""));
Edit: that wasn't what the OP wanted. I guess the problem is appending the stuff each time the event is triggered.
I'd say to create a DocumentFragment, put the new stuff in it, then appending to $("#content"). Unfortunately, DocumentFragments don't support innerHTML.
So, create a dummy element, fill it and then put its child nodes into the container:
var dummy = $("<div>").html(block), content = $("#content");
$.each(dummy.children(), function(i, c) {content.append(c);});
Adding html elements to the DOM represents a big performance penalty so it is better to create a big string and append it at the end, this post explains it really well
For most of your uses, the method of creating one really long string and appending it at the end will be the best choice, as it makes the best use of the trade offs of code legibility, ease of programming, and speed.
You could have your server return the values already marked-up in HTML, then:
$('#content').append( response );
You can then handle all of your looping and filtering server side, cutting down on the amount JS in your document.