Pass ajax result to HTML paragraph - html

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

Related

Replace bokeh object inside div on-click

I'm able to get the bokeh object to render properly inside a div on the webpage. The bokeh object is returned via Flask and is generated based on a user-click. However, my problem is that on every user-click, the new bokeh object that is produced, gets appended to the div.
I've read about the .html() way of replacing content, and I've also read about document.getElementById, but I'm not sure how to replace my div content and avoid the append. Any help is appreciated.
The relevant snippet from my index.html
rows.forEach(row => {
row.addEventListener("click", () => {
var pic = <<my_url>> + ($(row).attr("data-href"));
$.ajax({
data : {},
dataType: "json",
type : 'GET',
url : <<my flask app path>>
})
.then(function(response) {return response;})
.then(function(item) {
Bokeh.embed.embed_item(item);
})
});
});
emptying the contents of the div on-click is the approach I took to resolve my situation. i.e.,
$(div).empty();

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

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.

Best practise to display success in AJAX / HTML

I hava an Ajax function that GET all users information, and then pass it to the displayUser function.
In the displayUser function, i print it out in table with ID = displayUsers. This is working fine. But i now want to add more html code to this, without having a to dirty code. Does anyone have a good practice for this?
<script>
$(function () {
$.ajax({
type: 'GET',
url: '?page=getUserInfo',
dataType: 'json',
success: function(data) {
$.each(data, function(i, item){
displayUsers(item);
});
}
});
});
</script>
<script>
function displayUsers(item) {
var $displayUsers = $('#displayUsers');
$displayUsers.append('<tr><th>navn:</th><td>' + item.name + '</td><th>Brukernav:</th><td>' + item.username + '</td></tr>');
}
</script>
I have 2 thoughts. 1 what you are doing good and 2 what I can suggest (also brings in es2015 in discussion).
I see that you are creating an element and then appending it. It is really a good practice and is more performant because leads to less document repaint. You can extend this idea with more things like document.createElement. You can create 3 elements and then append them one by one to parent element. Although you may label it initially with bad looking code, it works great and is a good code.
You can also look into es2015 templates that supports multi line templates. Browsers have good support for it however I'm not sure if you do want to introduce es2015.

Json Table Sorting?

I have a table that populates prices from two apis. Unfortuantly this isn't sorted. Annoyingly. On each api however, it is sorted ^_^ So the issue i have is say site b is cheaper than site a. As it currenlty stands wouldn't work.
Heres my code. at the moment its just one api.
Forgot to mention, As it stands its site a ontop of site b in the same table. if there is a row thats cheaper tthen the row would have to move preferably.
Sam
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.length;i++) {
var title = json.results[i].section;
var price = json.results[i].price;
var href = json.results[i].quantity;
var button = "<button class='redirect-button' data-url='button link'>Link</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+href+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
So (assuming I understand this correctly), you want to have the rendered data be sorted by price? Luckily, that's easy to do :).
Here's a js fiddle so you can experiement: http://jsfiddle.net/e9sdb91v/
Here's the basic code you need:
success: function (data) {
var json = data.sort(sorter);
// Rest of your code goes here
}
You need to obviously write the sorter function as well:
function sorter(a, b) {
return (a.price - b.price);
}
That's basically it, sorter can be as simple or complex as you like (this will sort your objects from low to high on price). Just sort, then render.
If you need further clarification, just post a comment :).
Note: This sorts the data before rendering, so it assumes you are starting from scratch each time, if you are trying to add rows dynamically into the correct place in the #apple div, then that'll be slightly different (and you'll need to amend your question).

Prevent dynamic content loss on toggle

I am retrieving some data from the server and update the html contents of a div like this:
var req = new Request.JSON({
method: 'get',
url: 'index.php',
data: {},
onSuccess: function(r) {
$('my_div').set('html',r.output);
}
}
});
I wish to be able to 'toggle' the results as well and I use this:
var mySlide = new Fx.Slide('my_div');
$('toggle_link').addEvent('click', function(event){
event.stop();
mySlide.toggle();
event.stop();
});
This works only once presumably due to the fact that html contents are retrieved dynamically. Is there a way to prevent loosing the html contents from my Div and show the toggle effect?
Thanks!
To solve the problem about height, you need to set the resetHeight: true option to your Fx.Slide. Updated example here.