How to add spacing in the html() function in jquery? - html

Hello Guys!
See I have been creating a code powered with ajax but it is way too long and that's why I can't show it here, Sorry for this. But I have created a sample like thing in my Problem Demo link (below). You visit that page and see the problem by your own eyes! But here is the jQuery code of my sample ---
$(document).ready(function () {
$(document.body).html('
<div>
This is Complex Jquery Code Sample!
</div>
');
});
But when I enter my code in a single line (which I'm currently using in my original code) it shows everything perfect. But the problem is in my original code the HTML string is very long and so I'm unable to manage it quickly and effectively! Below is the link for the working one.
WORKING ONE
Hope you guys can help me out with this one. Or else I have to do a long coding on a single line which is very uncomfortable!
PROBLEM DEMO
THANKS IN ADVANCE

If you change your code to look like the following it should work.
Note the double quotes and the \ at the end of each line
$(document).ready(function () {
$(document.body).html("\
<div>\
This is Complex Jquery Code Sample!\
</div>\
");
});

I think you are asking for multi-line strings?
$(document).ready(function () {
$(document.body).html('\
<div>\
This is Complex Jquery Code Sample!\
</div>\
');
});

Do the following:
$(document).ready(function () {
$(document.body).html(''+
'<div>'+
'This is Complex Jquery Code Sample!'+
'</div>'+
'');
});

you can start writing your HTML using a DOM plugin it will be something like this
$(document.body).html($.DIV({}, "This is Complex jQuery Code Sample"));
a table would be something like this:
var table =
$.TABLE({ Class:"MyTable" },
$.TBODY({},
$.TR({ Class:"MyTableRow" },
$.TD({ Class:"MyTableCol1" }, 'howdy' ),
$.TD({ Class:"MyTableCol2" },
'Link: ',
$.A({ Class:"MyLink", href:"http://www.example.com" },
'example.com'
)
)
)
)
);
http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype

This looks like an excellent use case for jQuery templates.
http://stephenwalther.com/blog/archive/2010/03/16/microsoft-jquery-and-templating.aspx
Is that an option. It would be much easier to maintain a jquery template than it would be to edit large amounts of markup in js syntax.

I don't recommend you to hard-code long strings of HTML code into your JavaScript code. Instead, keep the HTML code inside a .html file, and then retrieve it via Ajax:
code.html:
<div>
This is Complex Jquery Code Sample!
</div>
JavaScript:
$.get('code.html', function(data) {
$('body').html(data);
});

Related

Summernote executes escaped html

I fetch data from a MySQL database, the data stored is this:
<p><script>alert('123');</script><br /></p>
When I fetch the data normally I get this as result:
<script>alert('123');</script>
This is fine and works as expected, however when I fetch the data into a textarea which is initialized with Summernote I get an alert like this:
Somehow Summernote converts the escaped html tags to functioning HTML.
How do I fix this?
I have already tried the answer of this question:
Escaped HTML in summernote
It did not work.
Why are you not sanitising data both at the time of storage, and when displayed in the Editor, or outside of the editor? Typically, in my CMS, I don't allow <script/> tags as way to help mitigate users adding potentially dangerous scripts.
That said, there is a PR that is being discussed about how we can best go about fixing this issue. https://github.com/summernote/summernote/pull/3782 information or help would be greatly appreciated to move it along, or even another PR fixing the issue.
I managed to fix it by instead of fetching the data in the textarea fetching it in via jQuery like this:
<textarea name="description" id="description"></textarea>
<script>
$('#description').summernote({
height: 250,
codeviewFilter: false,
codeviewIframeFilter: true,
// toolbar
toolbar: [
['font', ['bold', 'italic', 'underline', 'clear']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['view', ['fullscreen', 'codeview', 'help']]
],
}).on("summernote.enter", function(we, e) {
$(this).summernote('pasteHTML', '<br />&VeryThinSpace;');
e.preventDefault();
});
$("#description").summernote("code", "<?php echo $video->getDetails('', $fileName, 'desc'); ?>");
</script>
Now it doesn't convert > and $lt; to <> if it is the script tag.
See more information here:
https://github.com/summernote/summernote/pull/3782#issuecomment-774432392
Using javascript you can easily fix this. It worked for me in a React + Django project. I also used django_summer_note and it was also showing data like yours. Then I got that solution:
//simply just create a function like this which will return your data (which one you used with django_summernote).
const createBlog = () => {
return { __html: blog.description };
};
// now in your HTML(JSX) show your data like this.
<div className='' dangerouslySetInnerHTML={createBlog()} />

Backbone.js template: Render HTML from model?

I have an API that return HTML serialized in JSON accessed through a REST API. When I try to render the HTML from the API response, the HTML code is display as such:
<p>Hello this is a response!</p>, instead of as: Hello this is a response!
Is there any way to work around this?
Also, what are the potential security issues with doing this and actually render the HTML?
Best regards and help is much appreciated. :)
EDIT: Here are my models and my template. Sufficient to say, I'm new to Backbone.js, and this is mostly based on the Todos example.
Views:
app.DataView = Backbone.View.extend({
tagName: "li",
template: _.template($("#data-template").html()),
initialize: function() {
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
app.AppView = Backbone.View.extend({
el: "#htmldataapp",
initialize: function() {
app.datamodels.on('reset', this.addAll, this);
app.datamodels.fetch();
this.render();
},
addOne: function(datamodel) {
var view = new app.DataView({model: datamodel});
$('#data-list').append(view.render().el);
},
addAll: function() {
this.$('#data-list').html('');
app.datamodels.each(this.addOne, this);
}
});
Template:
<script type="text/template" id="data-template">
<%= data %>
</script>
You state that your api sends you HTML already?
So could it be that the data you get back is like <p>Hello this is a response!</p>, thus including the HTML tags?
If you would have underscore render this string in a template, it's no surprise you actually get the HTML tags to display.
Look at the generated source of the page, is the string Hello this is a response! wrapped in double <p> elements?
I would suggest changing your API in such a way that it returns data only (i.e. the string without the HTML), and have your HTML rendering be done by the underscore template engine.
Hope it helps!
EDIT:
I think you were using the underscore template function to often, causing the data to be rendered as a string.
Please see this fiddle for a sample setup how I think you should setup your app

With ng-bind-html-unsafe removed, how do I inject HTML?

I'm trying to use $sanitize provider and the ng-bind-htm-unsafe directive to allow my controller to inject HTML into a DIV.
However, I can't get it to work.
<div ng-bind-html-unsafe="{{preview_data.preview.embed.html}}"></div>
I discovered that it is because it was removed from AngularJS (thanks).
But without ng-bind-html-unsafe, I get this error:
http://errors.angularjs.org/undefined/$sce/unsafe
Instead of declaring a function in your scope, as suggested by Alex, you can convert it to a simple filter :
angular.module('myApp')
.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
Then you can use it like this :
<div ng-bind-html="preview_data.preview.embed.html | to_trusted"></div>
And here is a working example : http://jsfiddle.net/leeroy/6j4Lg/1/
You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe has been deprecated.
Instead, you'll want to do something like this:
<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>
In your controller, inject the $sce service, and mark the HTML as "trusted":
myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
$scope.preview_data.preview.embed.htmlSafe =
$sce.trustAsHtml(preview_data.preview.embed.html);
}
Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)
You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js
you need to include ngSanitize module on your app
eg: var app = angular.module('myApp', ['ngSanitize']);
you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.
For me, the simplest and most flexible solution is:
<div ng-bind-html="to_trusted(preview_data.preview.embed.html)"></div>
And add function to your controller:
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
Don't forget add $sce to your controller's initialization.
The best solution to this in my opinion is this:
Create a custom filter which can be in a common.module.js file for example - used through out your app:
var app = angular.module('common.module', []);
// html filter (render text as html)
app.filter('html', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text);
};
}])
Usage:
<span ng-bind-html="yourDataValue | html"></span>
Now - I don't see why the directive ng-bind-html does not trustAsHtml as part of its function - seems a bit daft to me that it doesn't
Anyway - that's the way I do it - 67% of the time, it works ever time.
You can create your own simple unsafe html binding, of course if you use user input it could be a security risk.
App.directive('simpleHtml', function() {
return function(scope, element, attr) {
scope.$watch(attr.simpleHtml, function (value) {
element.html(scope.$eval(attr.simpleHtml));
})
};
})
You do not need to use {{ }} inside of ng-bind-html-unsafe:
<div ng-bind-html-unsafe="preview_data.preview.embed.html"></div>
Here's an example: http://plnkr.co/edit/R7JmGIo4xcJoBc1v4iki?p=preview
The {{ }} operator is essentially just a shorthand for ng-bind, so what you were trying amounts to a binding inside a binding, which doesn't work.
I've had a similar problem. Still couldn't get content from my markdown files hosted on github.
After setting up a whitelist (with added github domain) to the $sceDelegateProvider in app.js it worked like a charm.
Description: Using a whitelist instead of wrapping as trusted if you load content from a different urls.
Docs: $sceDelegateProvider and ngInclude (for fetching, compiling and including external HTML fragment)
Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind. This is an unsafe option, but helpful when testing.
Example from the AngularJS documentation on $sce:
angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
Attaching the above config section to your app will allow you inject html into ng-html-bind, but as the doc remarks:
SCE gives you a lot of security benefits for little coding overhead.
It will be much harder to take an SCE disabled application and either
secure it on your own or enable SCE at a later stage. It might make
sense to disable SCE for cases where you have a lot of existing code
that was written before SCE was introduced and you're migrating them a
module at a time.
You can use filter like this
angular.module('app').filter('trustAs', ['$sce',
function($sce) {
return function (input, type) {
if (typeof input === "string") {
return $sce.trustAs(type || 'html', input);
}
console.log("trustAs filter. Error. input isn't a string");
return "";
};
}
]);
usage
<div ng-bind-html="myData | trustAs"></div>
it can be used for other resource types, for example source link for iframes and other types declared here

Conflict between jQuery Tools and another jQuery script

I'm using jQuery Tools(specifically, the form validator) and a JQuery Facebook-related script on one page of my website.
Each script requires referencing both an external file in the "head" of my HTML as well as a separate script in the "body" of my HTML.
Here is my code for the scripts in the "body" of my HTML (simplified):
First Script (Facebook script)
`
function init() {
FB.api('/me', function(response) {
$(".s_name").replaceWith('<input type="hidden" name="s_name" id="' + response.name + '" value="' + response.name + '" />');
..do more replaceWith stuff
});
}
//Live update of page as user selects recipient and gift options
$(".jfmfs-friend").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
...do stuff});
`
Second script (jQuery Tools - validator)
`
$("#form").validator({
position: 'top left',
offset: [-5, 0],
message: '<div><em/></div>',
singleError: true
});
`
Everything works correctly until the .click function of the first script is activated. At that point, the validator script stops working. I believe the issue is related to conflicting jQuery $'s, but I'm not sure how to fix it. I've tried using jQuery.noConflict() in various areas, but I haven't been successful and I'm not exactly sure how I should be using it.
Any help would be greatly appreciated!
Try using 'jQuery' in place of all '$' like so:
jQuery(document).ready(function() {}); as against $(document).ready...
I was forced to use the long version during a "conflict" of interest situations.

new to using the autocomplete with jquery

I am using the mvc pattern to pull in an autocomplete. I have searched around and apologize if this is a repeat question but I couldnt find my exact case which technically is very straighforward.
I have the following code:
<script type="text/javascript">
$(function() {
$( "#search" ).autocomplete({
source: "remote_bookmark.php?f=autocomplete",
minLength: 3,
select: function( event, ui ) {
ui.a.val;
ui.b.val;
ui.c.val;
ui.d.val;
}
});
});
</script>
this calls the remote page which calls a sql query in the model. The information is put into a multidimensional array that looks like the following in the model:
array_push($bookmark_array, array($row['a'],$row['b'], $row['c'], $row['d'], $row['e']));
I then echo the json_encode in the remote and after looking at the documentation still dont seem to follow how I am supposed to put the information in the select:
$( "#search" ).autocomplete({
source: "remote_bookmark.php?f=autocomplete",
minLength: 3
});
You do not need a select function unless you want to add extra functionality that is npt already there.
Just change your php to:
$bookmark_array = array($row['a'],$row['b'], $row['c'], $row['d'], $row['e']);
echo json_encode($bookmark_array);
And you should be all fine and dandy :-)