Best way to get ckeditor textarea value - javascript

I am not assured and really curious about this method of getting ckeditor value both are working well
bigMsg_Value = CKEDITOR.instances.editor1.getData();
var htmldata = CKEDITOR.instances.editor1.document.getBody().getHtml();
data that I get from both of that are seems like no difference, I wanna know which one is better and why.

getData() in ckeditor library:
getData: function( isSnapshot ) {
var data = this.getHtml();
if ( !isSnapshot )
data = this.editor.dataProcessor.toDataFormat( data );
return data;
}
As you can see internally ckeditor uses getHtml(). As per my opinion using getData() will be best as it is provided by the library.

Related

Assigning data to variables in React

I'm working with React and actual live data from a database for the first time. I'm using fetch as outlined in this article and that's working fine. I've been able to get data received from a php file to print into react.
I've run now into trouble because React kind of stopped making sense. Some variables will work just fine, while others that use the exact same data will not.
For example:
Given this array of objects
I can just do this to assign it to a variable:
var posts = this.props.postData.map(function(entry, index){
return <li>{entry.post_title}</li>;
})
And it will output just fine to this:
However, in the same function as the above, if I wanted to assign a specific string from the object to a variable, suddenly react will tell me the object is undefined.
var singlepost = <span>{this.props.postData[0].post_content}</span>
var singlepost = this.props.postData[0].post_content;
and even:
var singlepost = this.props.postData[0];
return (
<div>{singlepost.post_content}</div>
)
Will result in this:
No matter what I try React keeps telling me it's undefined, even though if I console.log the object right before using it its content will show in the console just fine. As soon as I specify the string I want, I will get an undefined error.
Is there a specific of doing this?
If your array is empty initially you need to check for that. You can do that with length:
if (this.props.postData.length) {
const { post_content } = this.props.postData[0];
return <div>{post_content}</div>;
}
return <div>No data</div>;;
you can do something like this
var singlepost = this.props.postData[0];
let post = null;
if(singlepost){
post = <div>{singlepost.post_content}</div>
}
return (
post
)
Maybe postData in first render is empty array. Just Add condition to render :
if(!this.props.postData.length) {
return null;
}
var singlepost = this.props.postData[0];
return (
<div>{singlepost.post_content}</div>
);
I prefer to do this way because get invalid cases out of the way first give code more clean.
You could also better your null check this way. It is a bit more verbose, but I appreciate the safety of it. It's also a bit of duplication
if (this.props.postData && this.props.postData.length > 0) {
// Do your computation here
}
Let me know if this meets your needs!

Dynamic table onclick

I have the following issue i would like to get some help for.
There is a combobox (select) where i choose an item and i get back a dinamic table from php. The table contains example names. Firstname, Lastname and ID(which is hidden). When i click on the table i get the value of the ID of the selected row. So far it is works fine. The problem that the event doesnt want to fire for first. After that it works fine but i need it for first as i have a function which auto click on the first row but this doesnt work until i solve this problem. I made a code which works fine with a html table. But not with the dinamic one. Please help.
Here is the code works fine with dinamic table but just after 2nd click:
function nametableclick() {
var rows = document.getElementById("nametable").rows;
for(var i = 0; i < rows.length; i++)
{
rows[i].onclick = function()
{
data=(this.cells[3].innerHTML);
var data = data;
$.ajax({
type: "POST",
url: "list.php",
data: "data="+data,
Type: "json",
success: function(msg) {
msg = JSON.parse(msg);
$("#dob").html(msg.dob);
$("#age").html(msg.age);
$("#sex").html(msg.sex);
}
});
};
};
};
And here is the code works well but just with html table:
(Actually is same but i use onload)
onload = function() {
var rows = document.getElementById("nametable").rows;
for(var i = 0; i < rows.length; i++)
{
rows[i].onclick = function()
{
data=(this.cells[3].innerHTML);
var data = data;
$.ajax({
type: "POST",
url: "list.php",
data: "data="+data,
Type: "json",
success: function(msg) {
msg = JSON.parse(msg);
$("#dob").html(msg.dob);
$("#age").html(msg.age);
$("#sex").html(msg.sex);
}
});
};
};
$("#nametable tr:eq(0) td:first-child").click();
};
When i use the onload function for the dinamic table it just doesnt work at all.
Thanks for any help in advance.
This question does not suit well for an answer. Instead, I'll do some code analysis.
onload = function() ... - well not terrible but kinda sloppy. Also looks like this is possible a global namespace leak. I'm going to assume this should be window.onload in which case I'd wonder why jQuery's ready event isn't used $(function() { ... }).
var rows = document.getElementById("nametable").rows;
for(var i = 0; i < rows.length; i++) {
rows[i].onclick = function() { ... };
}
Ok now were again running away from jQuery as if it was diseased some how. And then were looping over the array of rows only to construct a new function each time and attach them to the onclick (again avoiding jQuery)? Constructing functions inside a loop is a very bad idea and most linters will complain loudly about that. A suggestion:
$('#nametable tr').on('click', function() { ... });
This will attach the click handler to all the <TR> rows in the table with the id="nametable" attribute.
data=(this.cells[3].innerHTML);
var data = data;
My heart skipped a beat here!. First your pulling out the HTML content into (what I thought was a global variable) until I saw the next line and realized we have variable hoisting. But wait your assigning data to itself. Lastly, the name data doesn't provide any context as to the content of the innerHTML. Since I don't have the data I could only guess so in these examples I'll leave it as data. In the future think about picking names which provide context to their content and use. That way when you read the code you don't have to hunt for what the variables are for or how to use them.
var data = $(this, 'td:eq(3)').text();
Finally, the use of data is to directly concatenate it into a post request. I would assume HTML is not desired in that server API. Not to mention the avoidance of jQuery's parameter building by forcing the data to a string. Instead use a JS object:
$.ajax({
type: 'POST',
url: 'list.php',
data: {data: data} // This is a very poorly designed server API
}).then(function(data) {
...
});
Also, the use of Type: 'json' suggests that your server is not returning proper HTTP headers. First off there is no Type property for jQuery's ajax instead I think you wanted dataType. However the need for a dataType suggests the server is not sending the proper headers. If the PHP script were to return application/json instead of plain/text then jQuery could parse the response for you avoiding the need for JSON.parse on your own which can be a bit error prone.
$("#dob").html(msg.dob);
$("#age").html(msg.age);
$("#sex").html(msg.sex);
Be warned by using html() your directly injecting HTML into the DOM that you received from a third party. This is a big cross site scripting vulnerability. Use text() instead to push data into the DOM unless you know and can assert the trust of your server and the connection to it (SSL to avoid man in the middle). Probably not important for this example but still worth keeping in mind because it's far to easy to have this show up in the wild.
$("#nametable tr:eq(0) td:first-child")
When you have a selector like this it is far easier and readable to instead provide contextual hooks instead of relying on the make up of the DOM. Add things like class="clickable-row" or class="person-data dob" to your HTML markup. It makes for maintenance and readability.
Thanks for the quick reply. Im sure if there are lot of mistakes as i just started to learn this(i mean php html ajax ect.) a few weeks ago so i dont clearly understand everything and i use things i should not use or should do it another way. But there is a simple program i would like to make it done and learn from that. So when i dont know something im trying to get some info (like: w3schools.com) or check other topics which similar what im looking for.
Sorry i left there the
Var data = data;
My mistake. Dont need there. i was trying out something before and left there. Does not make any different anyway.
next:
The onload = function() {
i found in another topic as solved result and it works with a static table but not with dynamic.
I have tried the following. i did not mentioned:
window.onload = nametableclick;
function nametableclick() {
data here
}
But does not work with dynamic table either.
Next:
var rows = document.getElementById("nametable").rows;
for(var i = 0; i < rows.length; i++)
{
rows[i].onclick = function()
{
data2=(this.cells[3].innerHTML);
What it does for me it finds the selected row and comes back with the value of the 3rd(actually 4th) cell which is the ID in my prog. I need this cos i want to sent this value to the php to get all the data from the table where ID = the value. And it works fine.
As i mentioned the prog works fine even if it is not the best way to do it. Slowly i gonna learn how to do it better way. But at the moment the only problem with that is that the dynamic table onclick event fires only after the 1st click.
Thanks and sorry if im a bit hard case. :-)))
Oh 1 more thing:
"First off there is no Type property for jQuery's ajax instead I think you wanted dataType."
For some reason if i type dataType it just does not work at all. I have no idea why. I watched some training videos and read some short courses about ajax and some of them mentioned using dataType some of them just simple type. I followed everything but did not worked for me. i spent like 5 hours another day to find out why actually i have a topics here with that question as well.
get data from mysql with ajax and json into different textareas
And accidently i tried with uppercase T once and it worked. Have no idea why.

Filter json data in controller, the right way

(there are other questions but neither helped me out)
Hi, I would like to know if this is the right way to filter the results I get from service where I'm displaying only one result (like a detail).
I know I could use ng-repeat and filter it in the view and that is the cleanest, but I want to have more control over because I will re-use some of the data in the controller for other operations.
Right now I'm doing this:
$scope.savedEvents = Event.getPayedEvents(); //gets a list from service
//Goes through entire list and checks for a match
angular.forEach($scope.savedEvents, function(event) {
if (event.IdEvent == $stateParams.eventId) {
$scope.showEvent = event;
}
});
//now if there is a match I can use $scope.showEvent.eventName etc
Not sure if this would be easier using $filter to return just one event that has correct IdEvent. Or if someone has better solution, please let me know.
thanks
I don't see any problems with what you have, but you could inject the $filter service and do this one liner:
$scope.showEvent = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId });
EDIT: Here is an easy way to resolve the result to a single value from the returned array:
var showEvents = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId });
$scope.showEvent = showEvents && showEvents.length ? showEvents[0] : null;
In CoffeeScript it is a little more concise:
$scope.showEvent = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId })?[0]

Access JSON data from Backbone Router

In my bb router I get some JSON data
$.ajax({
url: "js/projects.json",
success: function(projects) {
database.projects = projects;
var variables = {};
var niz = new Array();
var param = "Client"
$.each(projects, function()
{
if (!variables[this[param]])
variables[this[param]] = [];
variables[this[param]].push(this);
});
for(var d in variables) {
niz.push(d);
var number_of_clients = niz.length;
}
console.log(number_of_clients);
Backbone.history.start();
}
});
Now I wanna access this "projects" from one of my Views and to some stuff with that data , I know I can do the same thing again like here , but its duplicating code , is there any way to get this data in View ? I tried a few things but with no success , I allways get the undefined
You can attach your data to the window (window.projects = projects), then you can access it from everywhere. But I recomend you to use the ajax tools from Backbone, it's much easier and less messy.
Honestly, your question seems very suspicious design-wise. :)
Ajax calls should be made in models using the fetch function, not in a router, and not using jquery directly.
So I would advise you to redesign your app unless you have a strong reason not to do so.

Sorting Dynamic Data with Isotope

I am trying to use Isotope.js to sort data by type. There seem to be a few ways to do this however they all require that you know the sort variables before hand.
One of the best examples of what I'm talking about is found in this question.
In the example they are trying to sort by class for example group all elements with class .milk like so:
milk: function( $elem ) {
var isMilk = $elem.hasClass('milk');
return (!isMilk?' ':'');
},
A jsfiddle is provided here: http://jsfiddle.net/Yvk9q/9/
My problem:
I am pulling the categories (classes or data-type) from a user generated database. For this reason I cannot simply add all the sorting variables to the code before hand.
I played with the fiddle and got a semi working sort here: http://jsfiddle.net/BandonRandon/erfXH/1/ by using data-category instead of class. However,this just sorts all data alphabetically not by actual category.
Some possible solutions:
Use JSON to return an array of all categories and then use this to loop through classes
Use inline javascript and run a PHP loop inside a <script> tag
Write an external PHP file with a javascript header
What I'm looking for
The simplest best approach here, being if it's one of the solutions above or something different. This doesn't seem like it should need to be this complicated. So I may be over complicating this.
EDIT:
I now have a json array of my data but I can't figure out how to pass the data into the isotope settings when i try something like this
var $container = $('.sort-container');
var opts = {
itemSelector: '.member-item',
layoutMode: 'straightDown',
getSortData : {
$.getJSON( 'member-cat-json.php', function(data) {
$.each(data, function(i, item) {
var slug = data[i].slug;
slug : function( $elem ) {
var is+slug = $elem.hasClass(slug);
return (!is+slug?' ':'');
}
}
});
});
}
}
var $container = $('.sort-container');
$container.isotope(opts);
It fails because I can't use a loop inside of the plugin settings. Not sure what can be done about this though.
EDIT 2:
I found this question which seems about what I'm trying to do but unfortunately the most recent jsfiddle fails with isotope
Here is a sample of my JSON output:
{term_id:9, name:Milk, slug:milk, term_group:0, term_taxonomy_id:17...}
{term_id:9, name:Eggs, slug:eggs, term_group:0, term_taxonomy_id:17...}
I am using the slug as the class name and in my loop.
I'm not sure I entirely understand your question, but I'll state my assumptions and work from there:
You have data in a format as described above:
{term_id:9, name:Milk, slug:milk, term_group:0, term_taxonomy_id:17...}
You want to sort on the slug names, even though we do not know what the slugs will be named ahead of time.
Assuming these two things, the fiddle you've linked to is close, but has a problem due to closures which I have fixed.
As expected, your situation is similar to the one listed, except that you need to obtain the JSON data first, as you have.
var $container = $('.sort-container'),
createSortFunction = function(slug) {
return function($elem) {
return $elem.hasClass(slug) ? ' ' : '';
};
},
getSortData = function(data) {
var sortMethods = {};
for (var index in data) {
var slug = data[index].slug;
// immediately create the function to avoid
// closure problems
sortMethods[slug] = createSortFunction(slug);
}
return sortMethods;
}
$.getJSON('member-cat-json.php', function (data) {
// I'm wrapping the isotop creation inside the `getJSON`
// call, just to ensure that we have `data`
$container.isotope({
itemSelector: '.member-item',
layoutMode: 'straightDown',
getSortData: getSortData(data);
});
});

Categories