3

In my project, I use Python Flask working as the server side and JS as the front end. The project allows user to select a photo and send the photo to the server side with AJAX post method. And server side will do image processing for this photo, and send back some data in JSON format about the image to the front end. The JS code goes as following:

$(document).ready(function(){
$("form").submit(function() {
    var form_data = new FormData($('#upload-file')[0]);
    $.ajax({
        type: 'POST',
        url: '/upload',
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        async: false,
        success: function(result) {
            var ctx = document.getElementById("result").getContext("2d");
            res = JSON.parse(result)
            var data = {
                labels: res['sentiment'],
                datasets: [
                    {
                        label: "Face Analysis",
                        fillColor: "white",
                        data: res['score']
                    }
                ]
            };
            var myLineChart = new Chart(ctx).Bar(data, {
                showScale: false
            });

        },
    });
return false; // so that form doesn't try to complete post
});

});

There is one confusing point for me, the final line return false, what is its function? If I remove this line, the app will fail. I find this from other resource, although there is comment after that, still can't figure out the meaning?

The Flask route goes as below:

@app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
    #print "post method"
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)

        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #return redirect(url_for('uploaded_file',filename=filename))
        result = image_analysis(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        print type(result)
        return json.dumps({'sentiment':result.keys(),'score':result.values()})
        #return json.dumps({'aftervalue':"baoqger"})
Chris Bao
  • 2,418
  • 8
  • 35
  • 62

1 Answers1

0

A form with a submit button will be submitted by the browser if the submit button is clicked, unless a javascript function is executed during the flow that returns false.

The original purpose of this is for validation:

(a) user enters data and clicks submit,
(b) js code is run to do form validation,
(c) form submit is prevented if validation code returned false.

Of course we now have Ajax which can submit on its own or do other magic. The return false; is and probably will always be needed to prevent the browser from doing (another) submit on its own.

Similar behaviour exists for e.g. hyperlinks: if an <a href has on onclick event that returns false, then clicking the hyperlink will run the js but won't navigate to the link.

Peter B
  • 22,460
  • 5
  • 32
  • 69