Flask with Summernote And Adding An image - Grabbing The Proper Data? - html

So im trying to get the information thats being grabbed via summernote textarea. When im not adding an image, everything works perfectly fine and I see the html content from the text editor.
But when I upload a picture, it suddenly gets stuck in a loop??? There more functionality that actually adds the info into the DB, and the image with that ridiculous img src, is saved, but for some reason its iterating the img src over and over? Since then Ive had everything commented out, only to print the textfield content, and for some reason, still get hit with an endless loop the moment I click the submit button? Any help is appreciated, thanks.
flask.py
#app.route("/update", methods=["POST"])
def update():
# Grab Text editor content from form:
contentInfo = request.form["content"]
print("TEST HERE", contentInfo)
html:
<form action="/update" method="POST">
<h1 style="text-align:center">content</h1><textarea name=content id="summernote">{{value}</textarea>
<input class="input-btn" type="submit" value="Update">
</form>
Script init inline within html:
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
minHeight: null,
maxHeight: null,
focus: true,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0],editor,welEditable);
}
});
});
</script>
So the text editor and everything works perfect, but the moment I add an image and click submit, my terminal gets stuck in an endless loop, literally need to trash the terminal in order to get it to stop before it crashes.
Any advice is appreciated, thanks.
Results: Over and Over...
Well Stack over flow wouldnt let me post an example, but it was just a bunch of what looked like the img src code from summernote over and over
Update: - So I changed a few things and at least got it to stop looping. I guess it was never looping what it was doing is literally printing out the content of whats being grabbed and apparently its a bunch of crap. I then instead trying to print it with certain params such as "content["img"] only to find out it was slices, so this is apparently an array: But I throw it into type, and it comes back with a class of "bytes" and a length of 529288.... lol! SO the printing wasnt a loop, it was literally printing the 500k lines of this stupid conversion... (super dumb that summernote compiles their images this way in my opinion)
Anyways, Wanted to post the current changes, I feel I am starting to get some progress as it is no longer stuck trying to print out 500k lines. Obviously the data thats being grabbed is the overall app converted into byes? becuase I feel the image conversion is around 7k characters, not 500k...
I feel my issue may be how im trying to grab the data? Since my app is flask and python, it has been a trial an error process trying to get it to work together with the inline javascript. So how my logic works here, is the moment a image is dropped into summernote, it gets thrown into the python logic "updateTest" All im trying to do here, is just grab the image data, so that I can manipulate and do as I wish with the results. How to go about properly grabbing this info? Any advice or insight is appreciated, thanks.
Updated Code:
html:
<form action="/updateTest" method="POST">
<h1 style="text-align:center">content</h1><textarea name=content id="summernote">{{value}</textarea>
<input class="input-btn" type="submit" value="Update">
flask.py:
#app.route("/updateTest", methods=["POST"])
def updateTest():
content = request.get_data()
print("test here", type(content))
print("test here2", len(content))
inline javascript within HTML:
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
focus: true,
callbacks: {
onImageUpload(files) {
sendFile(files[0], data => {
let imgNode = document.createElement("img");
imgNode.setAttribute('src', data.url)
$(this).summernote('insertNode', imgNode);
})
}
}
});
});
var sendFile = function(file, callback) {
var data;
data = new FormData();
data.append("file", file);
return $.ajax({
url: "/updateTest",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
return callback(data);
}
});
};
Any help on how to properly pull this file/image data is really what im looking for right now. Any help is appreciated, thanks

So I finally figured it out. Here is the proper code. now I originally wanted this to work with S3 buckets so in the end, going to that route right off the bat, rather than dealing with the crappy conversion summernote tries to do, I recommend everyone else doing the same thing when coming to something like this:
html:
<form action="/updateTest" method="POST">
<h1 style="text-align:center">content</h1><textarea name=content id="summernote">{{value}</textarea>
<input class="input-btn" type="submit" value="Update">
inline javascript within html:
<style>
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
focus: true,
callbacks: {
onImageUpload(files) {
sendFile(files[0], data => {
let imgNode = document.createElement("img");
imgNode.setAttribute('src', data.url)
$(this).summernote('insertNode', imgNode);
})
}
}
});
});
var sendFile = function(file, callback) {
var data;
data = new FormData();
data.append("file", file);
return $.ajax({
url: "/addImgSummer",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
return callback(data);
}
});
};
</style>
flask.py:
#app.route("/addImgSummer", methods=["POST"])
def addImgSummer():
#Grabbing file:
img = request.files["file"] #<------ THIS LINE RIGHT HERE! Is #literally all I needed lol.
# Below is me replacing the img "src" with my S3 bucket link attached, with the said filename that was added.
imgURL = "https://"+ S3_BUCKET_NAME +".s3.amazonaws.com/images/"+ img.filename
return jsonify(url = imgURL)
NOTE I have logic elsewhere that adds the data to the S3 bucket, the code above simply renders the result from my bucket. I plan on uploading my code to stack overflow on how to do a full s3 bucket situation with summernote. As this right here was just to finish the conclusion of my initial "Being stuck"
Anyways, hope this helps anyone who gets stuck where I did, as there is literally no proper documentation on how to utilize summernote with flask...(Dont get me wrong theres a lot, but none that work..) And even more so, NONE that utilize a better method than converting your image into a 7k byte character sequence, as I see most people doing... Just saving that horrid crap in their DB... So nothing properly working, at least not that I've found the past 3 days of searching..This right here, is the only working solution Ive come across.
The main confusion lies with mixing the javascript in the front end, and talking with your flask/python backend. Once you now how to grab that data, its smooth sailing.

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()} />

Pass ajax result to HTML paragraph

I'm probably missing something very obvious since I'm not familiar with ajax and it's been years since I touched html but I have a fairly simple function that calls an API via POST
// Predict
$('#btn-predict').click(function () {
var form_data = new FormData($('#upload-file')[0]);
// Show loading animation
$(this).hide();
$('.loader').show();
// Make prediction by calling api /predict
$.ajax({
type: 'POST',
url: '/DiabeticRetinopathy',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: true,
success: function (data) {
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').text(data[0]);
console.log('Success!');
},
});
});
And I can see the result in the html if I give it it's own dedicated section like
<h3 id="result">
<span> </span>
</h3>
But it's an float and I just wanted something simple like appending it to the end of a static paragraph
<p>Model Predictive Probability:<div class="result"></div> </p> <-doesn't work
I'm fairly sure that I'm using the wrong syntax somewhere. I can get around it by changing the python script in the backend to actually return the string "Model Predictive Probability: (insert float here)" to the ajax function instead of just returning the float but the end result is going to have several floats all with different strings and there's no way that's the easiest way to go about it
EDIT: I used div class= instead of div id= like an dummy. div id works just fine

Dynamically updated datalist won't show

I'm updating an html5 datalist dynamically, as the user types, with the following script:
$('#place').on('keyup', function() {
$.post('content/php/autocomp.php', { field: 'plaats', val: $('#place').val() }).done(function(response) {
$('#autocomp-places').html(response);
});
});
Which works fine except that the datalist often doesn't show right away. When I inspect the element the html is there but the datalist is not shown as soon as it's updated. How can I force it to show?
For the record: it works... I just wish it would always show the new suggestion right away.
Please use success instead of done method of ajax and try again.
$('#place').on('keyup', function () {
$.post('content/php/autocomp.php', {
field: 'plaats',
val: $('#place').val()
}).success(function (response) {
$('#autocomp-places').html(response);
});
});
I think I just have found a decent workaround for this!
Here is my pseudo-code:
As I type, I make async httprequests to get data.
When data is returned, i clear and re-populate the datalist.
If the current input field is still focused, manually call .focus() on the input element (this seems to force the data-list popup behavior to occur).
First, I would try to use one of already available solutions such as the jQuery UI autocomplete. It will shorten your development time and make the code free of typical bugs (not to mention getting the benefits from someone else work in the future).
If you really want to create your own version, I would make sure the list is cleared and repopulated with the following code:
$('#place').on('keyup', function() {
var posting = $.post('content/php/autocomp.php', { field: 'plaats', val: $('#place').val() });
posting.done(function(data) {
$('#autocomp-places').empty().append(data);
});
});

Json query - could not get results from array

I just making small code for tracking app to my website.
I'm pretty new at json so I could not find out what is wrong at my code. It's been two days now:
Here is the code
<http://code.jquery.com/jquery-latest.min.js>
<script type="text/javascript">
$(document).ready(function() {
var inputField = $('#tracking');
var outputElement = $('#textResult');
inputField.keyup(function() {
if (inputField.val().length > 1) {
$.getJSON('http://sporing.bring.no/sporing.json?q=' + inputField.val(),
function(data){
outputElement.html('ID' + data.consignmentSet.consignmentId);
});
} else {
outputElement.html('No result!');
}
});
});
</script>
<div>
<input type="text" id="tracking" style="width: 17;" maxlength="30"/><br/><span id="textResult"></span>
</div>
</body></html>
My source is: http://developer.bring.com/api/trackingapi.html#json
Tracking json source: http://sporing.bring.no/sporing.json?q=TESTPACKAGE-AT-PICKUPPOINT
Links gives result, but i'n not able to display it.
It is simple code, so hopefully someone can explain me what I'm doing wrong...
Thanks
data.consignmentSet contains an array with one element so
data.consignmentSet[0].consignmentId
should work!
You can use JSONLint to validate and pretty print your JSON to better dig into it's structure.
Also, you could use a debugger to explore the content of the data at runtime. Most browsers have their F12 developer tools or you could install Firebug. Then switch to the Script tab, go to the line in code where you access the data and click on the line number. A breakpoint will be set where code execution will stop when running the script. When the breakpoint is reached, you can explore the data in the Watch window.

Load a single record from a JSON API using Sencha Touch 2

I am having a horrible time understanding Sencha Touch 2's architecture. I'm finding even the most basic things I do in other language and frameworks to be incredibly painful.
Currently, I just want to do a standard Master/Detail view. I load a store into a list view and would like to click on each list item to slide in a detail view. Since my initial list view can contain quite a lot of items, I'm only loading a little bit of the data with this method in my controller:
viewUserCommand: function(list, record) {
// console.log(record);
var profileStore = Ext.getStore("Profiles");
profileStore.setProxy({
url: 'http://localhost:8000/profile/' + record.data.user_id
});
profileStore.load();
// console.log(profileStore);
Ext.Viewport.animateActiveItem(Ext.getCmp('profileview'), this.slideLeftTransition);
}
First, modifying the url property for each tap event seems a bit hacky. Isn't there a way to specify "this.id" or something along those lines, and then pass that to my store? Or would that require loading the entire DB table into an object?
I can console.log the return from this method and it's exactly what I want. How do I populate the detail view? I've tried utilizing a DataView component, but it doesn't show any data. The examples on sencha's website are fairly sparse, and relatively contextless. That means that even copying and pasting their examples are likely to fail. (Any examples I've tried using Ext.modelMgr.getModel() have failed.)
I know it's partly that this framework is new and I'm probably missing a huge gaping hole in my understanding of it, but does anyone have any clue?
Would suggest you check out the docs, there's an example of loading a single model:
http://docs.sencha.com/touch/2-0/#!/api/Ext.data.Model
Ext.define('User', {
extend: 'Ext.data.Model',
config: {
fields: ['id', 'name', 'email'],
proxy: {
type: 'rest',
url : '/users'
}
}
});
//get a reference to the User model class
var User = Ext.ModelManager.getModel('User');
//Uses the configured RestProxy to make a GET request to /users/123
User.load(123, {
success: function(user) {
console.log(user.getId()); //logs 123
}
});