login authentication using ajax call to flask server(Broken pipe) login authentication using ajax call to flask server(Broken pipe) flask flask

login authentication using ajax call to flask server(Broken pipe)


The javascript code should be included at the last (or delay the execution with $(document).ready). The code was trying to get the elements with document.getElementById("username").value before even the form fields were rendered. Apart from that, on clicking the submit button, the form gets normally submitted refreshing the page and rendering the ajax call previously useless. Also, the page refresh can interrupt the ajax call made previously, causing the broken pipe error that you see in the logs.

Here's a slightly better approach. Let's bind to the form submit event directly. Before that add id="loginForm" to the form so that we can fetch it directly with jQuery and also remove onclick attribute from submit button.

Now the javascript part.

$(document).ready(function() {    // bind the form submit event to our function    $("#loginForm").bind('submit', function(e) {        // prevent page refresh        e.preventDefault();        // post the data        var ajax=$.ajax({            type: "POST",            data: $("#loginForm").serialize(),            url: "http://localhost:8081/"        }).done(function(data){            console.log('done!')        });        ajax.fail(function(data){            console.log('error!');        });    });});

On the server end, get the form field data like request.form.get('username') and request.form.get('password').