Let's say in the database database, I want to have object which contains both letters and image, and i want to display them in the HTML.
I thought the most efficient way would be to encode the image in base64 and add it as an <img>
element in the string.
Therefore, it would look something like this:
<img width=''766'' height=''266'' src=''data: image/png; base64, Z29vZCBqb2IgZGVjb2Rpbmc=''>
To retrieve and display this information, following code is used:
function sendMsg(msg) {
var xhttp = new XMLHttpRequest();
var params = "msg=" + String(msg) + "&csrfmiddlewaretoken={{ csrf_token }}"
xhttp.open("POST", "/mtmessage/", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-Requested-With", "XmlHttpRequest");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var respo = JSON.parse(this.responseText)
document.getElementById("response_text").insertAdjacentHTML('beforeend', String(respo.rsp));
}
}
xhttp.send(params);
}
The first problem is, that the text takes too long to load in Ajax, i don't understand why is this exactly happening, maybe JSON parsing is slowing it down?
The second problem is that the image is not being displayed, the HTML still treats it as a string and not a DOM object, even though i tried insertAdjacentHTML
method.
What is the most proper way of doing this? should i pass this information differently?