0

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?

ShellRox
  • 2,532
  • 6
  • 42
  • 90
  • Whats wrong with `` and then just return the raw image instead of html? – Jonas Wilms Feb 25 '18 at 11:17
  • @JonasW. That would be possible, but then i would probably require multiple database queries, first one to obtain the text, and the second one to obtain the `img`. Or is there some other way? – ShellRox Feb 25 '18 at 11:21
  • I'm no database expert but I'm pretty sure you're optimizing query count at the expense of database size, bandwidth, and parse time. The [usual advice](https://stackoverflow.com/questions/5613898/storing-images-in-sql-server#5613926) seems to be to store small images as binary blobs (not text), and large images in the filesystem. (Meanwhile, watch out for that `width=''766''` thing. Should be `width="766"`: two single quotes isn't the same as one double quote, and is invalid HTML. Which probably explains why the HTML isn't rendering.) – Daniel Beck Feb 25 '18 at 16:14

0 Answers0