Flask flash and url_for with AJAX

I'll take a stab at this, but I'm not sure I understand the problem completely :D. The code below isn't tested, it is more along the lines of pseudocode!

Your first problem is (if I understand you correctly) that you are doing partial updates via ajax, and wanting to fetch the update results later after the partial updates. Instead of fetching update results later, you should return them after each ajax call. So, if you have update code that looks like this:

data = $('#my-form').serialize()
$.post(update_url, data, function (results) {
    // Here you check results.
    if (results.success) {
        $('#update-div').message('Update Success')
    } else {
        $('#update-div').message('Update Failed: ' + results.error_msg)
    }
})

Then your update route would have code similar to this:

from flask import jsonify

@app.route('/partialupdate/<int:userid>', methods=['POST'])
def partial_update(userid):
    try:
        # fetch the user, perform the updates and commit
        return jsonify(success=1)
    except Exception, e:
        return jsonify(success=0, error_msg=str(e))

Your second problem involving URL generation can be fixed by using USERID instead of client name. NEVER use client name for anything other than searches :D. In this case use user id. The user id is typically the primary key for a particular user in a database. If you're not using a database, then generate your own user id's somehow and attach it to a user - it should be a unique number per user. Using a user id means that you can always edit with urls like '/edituser/1'.


I have had this requirement as well. To flesh out Paul Wand's answer, here is how I did it (note, the markup generated is for bootstrap 3:

put an empty div for the flash messages in the template:

<div id="flash"></div>

your ajax call:

$.post("/foo/bar", JSON.stringify({'calls': 'whatever'}), function(returnedData) {
    $('#flash').append(flashMessage(JSON.parse(returnedData)));
});

And use the parsing function:

var flashMessage = function(data){
  html = '';
  for (i=0; i<data.length; i++) {
    html += '<div class="alert alert-' + data[i]['type'] + '"><a href="#" class="close" data-dismiss="alert">&times;</a>' + data[i].message + '</div>';
  }
  return html;
};

in your route that handles the AJAX request, simply return a JSON object that looks like:

[{'type': 'success', 'message': 'Here is a message'}]

where the 'type' is a bootstrap 3 status type, ie. success, info, warning, danger. The dict gets wrapped in a list, so you can pass multiple if you need to.

The JSON.parse is not required if the response is already jsonified. In that case the code is simply:

$('#flash').append(flashMessage(returnedData));

Also, if you don't need multiple flash messages, simply replace 'append' with 'html'