Flask with Javascript Flask with Javascript flask flask

Flask with Javascript


Try jQuery ajax:

function upload() {    // Generate the image data    var img= document.getElementById("myCanvas").toDataURL("image/png");    img = img.replace(/^data:image\/(png|jpg);base64,/, "")    // Sending the image data to Server    $.ajax({        type: 'POST',        url: '/upload',              // /new         data: '{ "imageData" : "' + img + '" }',        contentType: 'application/json; charset=utf-8',        dataType: 'json',        success: function (msg) {        // On success code        }    });}

Rest is get uploaded image data at server side using request.json['imageData'] and store it in database.

img = request.json['imageData'] # Store this in DB (use blob)


What you have to do is to use AJAX, the technique to "asynchronously" send requests and get responses from a server after the page is loaded on the client's browser, using JavaScript.AJAX, in fact, stands for Asynchronous JavaScript And XML (even though it doesn't necessarily have to be neither completely asynchronous, nor you must resort to XML as a data exchange format). This is the standard way to access Web APIs, such as the one you crafted with Flask by exposing the ability to retrieve and persiste objects in your backend through URLs (the ones represented the the routes).

Modern browsers consistently expose the XMLHttpRequest constructor (MDN documentation) that can be used to create objects that allow the page to communicate with your Web server once it's loaded.

To improve cross-browser compatibility and code maintainability, you can resort to JavaScript frameworks that "wrap" the XMLHttpRequest with their own abstractions. I've been productively using jQuery for years for this purpose. In particular, in your case you would need the jQuery.ajax method (or, for POST operations, it's shorthand jQuery.post).

However I'll give you a small example of how to perform such request using vanilla JS so that you can understand what's going on in the browser even when using a framework:

// Create an instance of the XHR objectvar postNewObject = new XMLHttpRequest();// Define what the object is supposed to do once the server respondspostNewObject.onload = function () {  alert('Object saved!');};// Define the method (post), endpoint (/new) and whether the request// should be async (i.e. the script continues after the send method// and the onload method will be fired when the response arrives)postNewObject.open("post", "/new", true);// Send! postNewObject.send(/* Here you should include the form data to post */);// Since we set the request to be asynchronous, the script// will continue to be executed and this alert will popup// before the response arrivesalert('Saving...');

Refer to MDN for more details about using the XMLHttpRequest.