I am writing Python Pyramid project and I use jQuery and jquery.form.js. I want my views to handle both HTTP and AJAX posts (I am not sure if it is best idea, but this is probably the stuff for another question here).
Now I use self.request.session.flash() for error notification when HTTP POST was send and error happened.
But when Ajax is posted, I return HTTPOk() or HTTPServerError() response so then I can easy show error message to the user:
$('.ajax_form').ajaxForm({
error: function(xhr, textStatus, err){
$('.ajax_messages>.alert').hide().siblings('.alert-error').show().children('p').text(xhr.responseText);
},
success: function(responseText, statusText, xhr){
$('.ajax_messages>.alert').hide().siblings('.alert-success').show().children('p').text(xhr.responseText);
}
});
But as Loïc Faure-Lacroix suggested I could send dict for both Ajax and HTTP requests and that way simplify the code.
What is better idea? What should I return from view when an exception was thrown?
The idea is to return a dict that contains the values you want in the json response. This dict may be rendered via json or via your template. In an error condition you can set the response status to 500. This works if everything you’re doing is identical (same data needed for json and for html, same response codes). Otherwise your life will be difficult and it’s best to just separate it.
All you have to do is make sure that your template can handle ‘status’ and ‘error_msg’ fields and you’re good to go. Again, this only works well if the template’s requirements are a subset of what you’re returning for json.