From 0c2a27bdbae6bf0cf06a1f99aceceb2afa116dae Mon Sep 17 00:00:00 2001 From: Antoine Nguyen Date: Tue, 29 Oct 2013 21:31:37 +0100 Subject: [PATCH] ajax_simple_response removed. see #491 --- modoboa/demo/views.py | 12 +- modoboa/extensions/admin/views/domain.py | 7 +- modoboa/extensions/admin/views/identity.py | 12 +- .../amavis/static/amavis/js/quarantine.js | 20 ++- .../amavis/static/amavis/js/selfservice.js | 11 +- modoboa/extensions/amavis/views.py | 28 ++-- .../postfix_relay_domains/js/relay_domains.js | 6 +- .../static/sievefilters/js/lib.js | 46 ++---- .../extensions/stats/static/stats/js/stats.js | 4 - modoboa/extensions/stats/views.py | 13 +- .../webmail/static/webmail/js/webmail.js | 134 +++++++----------- modoboa/extensions/webmail/views.py | 39 +++-- modoboa/lib/webutils.py | 11 -- modoboa/static/js/confirmation.js | 12 +- modoboa/static/js/creation_wizard.js | 64 ++++----- modoboa/static/js/global.js | 37 +++-- modoboa/static/js/history.js | 24 ++-- modoboa/static/js/poller.js | 25 ++-- 18 files changed, 212 insertions(+), 293 deletions(-) diff --git a/modoboa/demo/views.py b/modoboa/demo/views.py index 19b9e14ea..18e2a8427 100755 --- a/modoboa/demo/views.py +++ b/modoboa/demo/views.py @@ -3,10 +3,11 @@ import os from django.conf import settings from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ -from modoboa.lib.webutils import ajax_simple_response +from modoboa.lib.webutils import render_to_json_response from modoboa.lib.emailutils import sendmail_simple, sendmail_fromfile from modoboa.lib.decorators import needs_mailbox + @login_required @needs_mailbox() def send_virus(request): @@ -14,8 +15,9 @@ def send_virus(request): os.path.join(settings.MODOBOA_DIR, "tmp/virus.msg")) if status: - return ajax_simple_response(dict(status="ok", respmsg=_("Message sent"))) - return ajax_simple_response(dict(status="ko", respmsg=error)) + return render_to_json_response(_("Message sent")) + return render_to_json_response(error, status=500) + @login_required @needs_mailbox() @@ -38,5 +40,5 @@ XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X You should send this test mail from an account outside of your network. """) if status: - return ajax_simple_response(dict(status="ok", respmsg=_("Message sent"))) - return ajax_simple_response(dict(status="ko", respmsg=error)) + return render_to_json_response(_("Message sent")) + return render_to_json_response(respmsg=error, status=500) diff --git a/modoboa/extensions/admin/views/domain.py b/modoboa/extensions/admin/views/domain.py index 29b43132c..38cd61f10 100644 --- a/modoboa/extensions/admin/views/domain.py +++ b/modoboa/extensions/admin/views/domain.py @@ -9,8 +9,7 @@ from django.contrib.auth.decorators import ( ) from modoboa.lib import parameters, events from modoboa.lib.webutils import ( - ajax_simple_response, _render_to_string, - render_to_json_response + _render_to_string, render_to_json_response ) from modoboa.lib.formutils import CreationWizard from modoboa.lib.exceptions import ( @@ -53,7 +52,7 @@ def _domains(request): domainlist = sorted(domainlist, key=lambda d: d.tags[0], reverse=sort_dir == '-') page = get_listing_page(domainlist, request.GET.get("page", 1)) - return ajax_simple_response({ + return render_to_json_response({ "table": _render_to_string(request, 'admin/domains_table.html', { 'domains': page.object_list, 'tableid': 'domains' @@ -82,7 +81,7 @@ def domains(request, tplname="admin/domains.html"): @permission_required("core.add_user") def domains_list(request): doms = [dom.name for dom in Domain.objects.get_for_admin(request.user)] - return ajax_simple_response(doms) + return render_to_json_response(doms) @login_required diff --git a/modoboa/extensions/admin/views/identity.py b/modoboa/extensions/admin/views/identity.py index 7ab550a68..e44ac9d87 100644 --- a/modoboa/extensions/admin/views/identity.py +++ b/modoboa/extensions/admin/views/identity.py @@ -11,8 +11,7 @@ from modoboa.lib.exceptions import ( ModoboaException, PermDeniedException, BadRequest ) from modoboa.lib.webutils import ( - ajax_simple_response, _render_to_string, - render_to_json_response + _render_to_string, render_to_json_response ) from modoboa.lib.formutils import CreationWizard from modoboa.lib.templatetags.lib_tags import pagination_bar @@ -44,7 +43,7 @@ def _identities(request): objects = sorted(idents_list, key=lambda o: o.tags[0], reverse=sort_dir == '-') page = get_listing_page(objects, request.GET.get("page", 1)) - return ajax_simple_response({ + return render_to_json_response({ "table": _render_to_string(request, "admin/identities_table.html", { "identities": page.object_list, "tableid": "objects_table" @@ -74,7 +73,7 @@ def accounts_list(request): accs = User.objects.filter(is_superuser=False) \ .exclude(groups__name='SimpleUsers') res = [a.username for a in accs.all()] - return ajax_simple_response(res) + return render_to_json_response(res) @login_required @@ -103,8 +102,7 @@ def list_quotas(request, tplname="admin/quotas.html"): else: raise BadRequest(_("Invalid request")) page = get_listing_page(mboxes, request.GET.get("page", 1)) - return ajax_simple_response({ - "status": "ok", + return render_to_json_response({ "page": page.number, "paginbar": pagination_bar(page), "table": _render_to_string(request, tplname, { @@ -231,4 +229,4 @@ def remove_permission(request): if not request.user.can_access(account) or not request.user.can_access(domain): raise PermDeniedException domain.remove_admin(account) - return ajax_simple_response({"status": "ok"}) + return render_to_json_response({}) diff --git a/modoboa/extensions/amavis/static/amavis/js/quarantine.js b/modoboa/extensions/amavis/static/amavis/js/quarantine.js index 699c37252..bb4b8ff57 100644 --- a/modoboa/extensions/amavis/static/amavis/js/quarantine.js +++ b/modoboa/extensions/amavis/static/amavis/js/quarantine.js @@ -117,9 +117,8 @@ Quarantine.prototype = { url: $link.attr("href"), data: "action=" + name + "&selection=" + selection.join(","), type: 'POST', - dataType: 'json', - success: $.proxy(this.action_cb, this) - }); + dataType: 'json' + }).done($.proxy(this.action_cb, this)); }, release_selection: function(e) { @@ -139,9 +138,8 @@ Quarantine.prototype = { } $.ajax({ url: $link.attr("href"), - dataType: 'json', - success: $.proxy(this.action_cb, this) - }); + dataType: 'json' + }).done($.proxy(this.action_cb, this)); }, release: function(e) { @@ -175,11 +173,11 @@ Quarantine.prototype = { if (!$rawheaders.length) { $.ajax({ url: $link.attr("href"), - success: $.proxy(function(data) { - $mailcontent.find("#table-container").append($(data)); - this.show_rawheaders($mailcontent); - }, this) - }); + global: false + }).done($.proxy(function(data) { + $mailcontent.find("#table-container").append($(data)); + this.show_rawheaders($mailcontent); + }, this)); return; } this.show_rawheaders($mailcontent); diff --git a/modoboa/extensions/amavis/static/amavis/js/selfservice.js b/modoboa/extensions/amavis/static/amavis/js/selfservice.js index 8aecf6d04..d634f9bfa 100644 --- a/modoboa/extensions/amavis/static/amavis/js/selfservice.js +++ b/modoboa/extensions/amavis/static/amavis/js/selfservice.js @@ -7,14 +7,9 @@ function send_action(e, message) { } $.ajax({ url: $link.attr("href"), - dataType: 'json', - success: function(data) { - if (data.status == "ok") { - $("body").notify("success", data.respmsg, 2000); - } else { - $("body").notify("error", data.respmsg); - } - } + dataType: 'json' + }).done(function(data) { + $("body").notify("success", data, 2000); }); } diff --git a/modoboa/extensions/amavis/views.py b/modoboa/extensions/amavis/views.py index 261110f2c..f1973b966 100644 --- a/modoboa/extensions/amavis/views.py +++ b/modoboa/extensions/amavis/views.py @@ -10,13 +10,15 @@ from django.contrib.auth.decorators \ import login_required, user_passes_test from django.db.models import Q from modoboa.lib import parameters -from modoboa.lib.exceptions import ModoboaException +from modoboa.lib.exceptions import ModoboaException, BadRequest from modoboa.lib.webutils import ( - getctx, ajax_response, ajax_simple_response + getctx, ajax_response, render_to_json_response ) from modoboa.lib.email_listing import parse_search_parameters from modoboa.extensions.admin.models import Mailbox, Domain -from templatetags.amavis_tags import quar_menu, viewm_menu +from modoboa.extensions.amavis.templatetags.amavis_tags import ( + quar_menu, viewm_menu +) from .lib import selfservice, AMrelease from .sql_listing import SQLlisting, SQLemail, get_wrapper from .models import Msgrcpt @@ -79,7 +81,7 @@ def _listing(request): rcptfilter = request.session["pattern"] continue else: - raise Exception("unsupported search criteria %s" % c) + raise BadRequest("unsupported search criteria %s" % c) flt = nfilter if flt is None else flt | nfilter msgs = get_wrapper().get_mails(request, rcptfilter) @@ -202,14 +204,14 @@ def check_mail_id(request, mail_id): def delete_selfservice(request, mail_id): rcpt = request.GET.get("rcpt", None) if rcpt is None: - raise ModoboaException(_("Invalid request")) + raise BadRequest(_("Invalid request")) try: msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) msgrcpt.rs = 'D' msgrcpt.save() except Msgrcpt.DoesNotExist: - raise ModoboaException(_("Invalid request")) - return ajax_simple_response(dict(status="ok", respmsg=_("Message deleted"))) + raise BadRequest(_("Invalid request")) + return render_to_json_response(_("Message deleted")) @selfservice(delete_selfservice) @@ -241,13 +243,13 @@ def release_selfservice(request, mail_id): rcpt = request.GET.get("rcpt", None) secret_id = request.GET.get("secret_id", None) if rcpt is None or secret_id is None: - raise ModoboaException(_("Invalid request")) + raise BadRequest(_("Invalid request")) try: msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) except Msgrcpt.DoesNotExist: - raise ModoboaException(_("Invalid request")) + raise BadRequest(_("Invalid request")) if secret_id != msgrcpt.mail.secret_id: - raise ModoboaException(_("Invalid request")) + raise BadRequest(_("Invalid request")) if parameters.get_admin("USER_CAN_RELEASE") == "no": msgrcpt.rs = 'p' msg = _("Request sent") @@ -258,9 +260,9 @@ def release_selfservice(request, mail_id): rcpt.rs = 'R' msg = _("Message released") else: - raise ModoboaException(result) + raise BadRequest(result) msgrcpt.save() - return ajax_simple_response(dict(status="ok", respmsg=msg)) + return render_to_json_response(msg) @selfservice(release_selfservice) @@ -329,4 +331,4 @@ def process(request): @user_passes_test(lambda u: u.group != 'SimpleUsers') def nbrequests(request): result = get_wrapper().get_pending_requests(request.user) - return ajax_simple_response(dict(status="ok", requests=result)) + return render_to_json_response({'requests': result}) diff --git a/modoboa/extensions/postfix_relay_domains/static/postfix_relay_domains/js/relay_domains.js b/modoboa/extensions/postfix_relay_domains/static/postfix_relay_domains/js/relay_domains.js index f14188ee0..fc454ab39 100644 --- a/modoboa/extensions/postfix_relay_domains/static/postfix_relay_domains/js/relay_domains.js +++ b/modoboa/extensions/postfix_relay_domains/static/postfix_relay_domains/js/relay_domains.js @@ -33,7 +33,8 @@ RelayDomains.prototype = { e.preventDefault(); $.ajax({ type: "POST", - url: $link.attr("href") + url: $link.attr("href"), + global: false }).done(function(data) { var $widget = $('#id_service'); @@ -48,9 +49,6 @@ RelayDomains.prototype = { build_success_alert(gettext('Services updated')) ); }).fail(function(jqxhr) { - if (jqxhr.getResponseHeader('Content-Type') != 'application/json') { - return; - } var result = $.parseJSON(jqxhr.responseText); $('.modal-body').prepend( build_error_alert(result[0]) diff --git a/modoboa/extensions/sievefilters/static/sievefilters/js/lib.js b/modoboa/extensions/sievefilters/static/sievefilters/js/lib.js index 3c8336806..700a4e423 100644 --- a/modoboa/extensions/sievefilters/static/sievefilters/js/lib.js +++ b/modoboa/extensions/sievefilters/static/sievefilters/js/lib.js @@ -22,9 +22,6 @@ function removefilter(evt) { }).done(function(response) { history.update(true); $("body").notify('success', response, 2000); - }).fail(function(jqxhr) { - var response = $.parseJSON(jqxhr.responseText); - $("body").notify('error', response); }); } @@ -75,20 +72,15 @@ function loadfs(response) { function send_command(cmd, extracb) { $.ajax({ url: cmd, - dataType: 'json', - success: function(response) { - if (response.status == "ko") { - $("body").notify('error', response.respmsg); - } else { - if (extracb != undefined) { - extracb(response); - } - if (!response.norefresh) { - history.update(true); - } - $("body").notify('success', response.respmsg, 2000); - } + dataType: 'json' + }).done(function(response) { + if (extracb != undefined) { + extracb(response); } + if (!response.norefresh) { + history.update(true); + } + $("body").notify('success', response.respmsg, 2000); }); } @@ -121,14 +113,9 @@ function savefs(evt) { url: $editor.attr("action"), type: $editor.attr("method"), dataType: 'json', - data: $editor.serialize(), - success: function(response) { - if (response.status == "ko") { - $("body").notify('error', response.respmsg); - } else { - $("body").notify('success', response.respmsg, 2000); - } - } + data: $editor.serialize() + }).done(function(response) { + $("body").notify('success', response.respmsg, 2000); }); } @@ -184,9 +171,6 @@ function toggle_filter_state(event) { $this.html(response.label); $this.attr("class", ""); $this.addClass(response.color); - }).fail(function(jqhxr) { - var response = $.parseJSON(jqxhr.responseText); - $("body").notify('error', response); }); } @@ -200,9 +184,6 @@ function move_filter(event) { }).done(function(response) { $("#set_content").html(response.content); init_filters_list(); - }).fail(function(jqxhr) { - var response = $.parseJSON(jqxhr.responseText); - $("body").notify('error', response); }); } @@ -254,8 +235,9 @@ function fetch_templates(url, container) { $.ajax({ url: url, async: false, - dataType: 'json', - success: function(data) { result = data; } + dataType: 'json' + }).done(function(data) { + result = data; }); return result; } \ No newline at end of file diff --git a/modoboa/extensions/stats/static/stats/js/stats.js b/modoboa/extensions/stats/static/stats/js/stats.js index 557ef7786..fcf21a5ff 100644 --- a/modoboa/extensions/stats/static/stats/js/stats.js +++ b/modoboa/extensions/stats/static/stats/js/stats.js @@ -79,10 +79,6 @@ Stats.prototype = { }, graphs_cb: function(data) { - if (data.status == "ko") { - $("body").notify("error", data.respmsg); - return; - } if (data.content) { $(".tab-pane.active").html(data.content); } diff --git a/modoboa/extensions/stats/views.py b/modoboa/extensions/stats/views.py index b9fee9083..accd7608f 100644 --- a/modoboa/extensions/stats/views.py +++ b/modoboa/extensions/stats/views.py @@ -7,7 +7,7 @@ from django.contrib.auth.decorators import ( from modoboa.lib import events from modoboa.lib.exceptions import ModoboaException, PermDeniedException from modoboa.lib.webutils import ( - _render_to_string, ajax_simple_response + _render_to_string, render_to_json_response ) from modoboa.extensions.admin.models import ( Domain @@ -50,7 +50,7 @@ def graphs(request): if searchq in [None, "global"]: if not request.user.is_superuser: if not Domain.objects.get_for_admin(request.user).count(): - return ajax_simple_response({"status": "ok"}) + return render_to_json_response({}) tplvars.update( domain=Domain.objects.get_for_admin(request.user)[0].name ) @@ -59,7 +59,7 @@ def graphs(request): else: domain = Domain.objects.filter(name__contains=searchq) if domain.count() != 1: - return ajax_simple_response({"status": "ok"}) + return render_to_json_response({}) if not request.user.can_access(domain[0]): raise PermDeniedException tplvars.update(domain=domain[0].name) @@ -83,7 +83,6 @@ def graphs(request): else: tplvars['graphs'] = gsets[gset].get_graph_names() - return ajax_simple_response(dict( - status="ok", - content=_render_to_string(request, "stats/graphs.html", tplvars) - )) + return render_to_json_response({ + 'content': _render_to_string(request, "stats/graphs.html", tplvars) + }) diff --git a/modoboa/extensions/webmail/static/webmail/js/webmail.js b/modoboa/extensions/webmail/static/webmail/js/webmail.js index 829c477ac..d3440efd7 100644 --- a/modoboa/extensions/webmail/static/webmail/js/webmail.js +++ b/modoboa/extensions/webmail/static/webmail/js/webmail.js @@ -261,8 +261,8 @@ Webmail.prototype = { * Poller callback. */ poller_cb: function(data) { - for (var mb in data.counters) { - this.set_unseen_messages(mb, parseInt(data.counters[mb])); + for (var mb in data) { + this.set_unseen_messages(mb, parseInt(data[mb])); } }, @@ -341,14 +341,10 @@ Webmail.prototype = { url: this.options.submboxes_url, dataType: 'json', async: async, - data: "topmailbox=" + parent.attr("name"), - success: $.proxy(function(data) { - if (data.status == "ko") { - return; - } - this.inject_mailboxes(parent, data.mboxes); - }, this) - }); + data: "topmailbox=" + parent.attr("name") + }).done($.proxy(function(data) { + this.inject_mailboxes(parent, data); + }, this)); }, /* @@ -482,17 +478,12 @@ Webmail.prototype = { $.ajax({ url: $link.attr("href") + "?name=" + $selected.attr("href"), - dataType: 'json', - success: $.proxy(function(data) { - if (data.status == "ok") { - this.remove_mbox_from_tree(this.navobject.getparam("mbox")); - this.poller.resume(); - $("body").notify("success", gettext("Mailbox removed"), 2000); - } else { - $("body").notify("error", data.respmsg); - } - }, this) - }); + dataType: 'json' + }).done($.proxy(function(data) { + this.remove_mbox_from_tree(this.navobject.getparam("mbox")); + this.poller.resume(); + $("body").notify("success", gettext("Mailbox removed"), 2000); + }, this)); }, /* @@ -587,25 +578,19 @@ Webmail.prototype = { $.ajax({ url: $link.attr("href"), data: "ids=" + selection.join(","), - dataType: 'json', - success: $.proxy(this.mark_callback, this) - }); + dataType: 'json' + }).done($.proxy(this.mark_callback, this)); }, send_mb_action: function(url, cb) { $.ajax({ url: url, - dataType: 'json', - success: $.proxy(function(data) { - if (data.status == "ko") { - $("body").notify("error", data.respmsg); - return; - } - if (cb != undefined) { - cb.apply(this, [data]); - } - }, this) - }); + dataType: 'json' + }).done($.proxy(function(data) { + if (cb != undefined) { + cb.apply(this, [data]); + } + }, this)); }, empty: function(e) { @@ -629,8 +614,8 @@ Webmail.prototype = { e.preventDefault(); $.ajax({ url: $link.attr("href"), - success: $.proxy(this.delete_callback, this) - }); + dataType: 'json' + }).done($.proxy(this.delete_callback, this)); }, delete_messages: function(e) { @@ -658,9 +643,8 @@ Webmail.prototype = { this.change_unseen_messages(this.options.trash, unseen_cnt); $.ajax({ url: $link.attr("href"), - data: {mbox: this.get_current_mailbox(), selection: selection}, - success: $.proxy(this.delete_callback, this) - }); + data: {mbox: this.get_current_mailbox(), selection: selection} + }).done($.proxy(this.delete_callback, this)); }, display_mode: function(e, value) { @@ -737,8 +721,18 @@ Webmail.prototype = { data: args, dataType: 'json', type: 'POST', - success: $.proxy(this.sendmail_callback, this) - }); + global: false + }).done($.proxy(function(data) { + this._listmailbox_loader(null, $("#folders").find("li[class*=active]").children("a")); + $("body").notify("success", gettext("Message sent"), 2000); + }, this)).fail($.proxy(function(jqxhr) { + var data = $.parseJSON(jqxhr.responseText); + this.navobject.get_callback("compose")(data); + if (data.respmsg != undefined) { + $("body").notify("error", data.respmsg); + } + $("a[name=sendmail]").attr("disabled", null); + }, this)); }, /* @@ -833,19 +827,6 @@ Webmail.prototype = { }); }, - sendmail_callback: function(data) { - if (data.status == "ko") { - this.navobject.get_callback("compose")(data); - if (data.respmsg != undefined) { - $("body").notify("error", data.respmsg); - } - $("a[name=sendmail]").attr("disabled", null); - return; - } - this._listmailbox_loader(null, $("#folders").find("li[class*=active]").children("a")); - $("body").notify("success", gettext("Message sent"), 2000); - }, - /* * Callback of the 'viewmail' action */ @@ -859,10 +840,6 @@ Webmail.prototype = { }, mark_callback: function(data) { - if (data.status == "ko") { - $("body").notify("error", data.respmsg); - return; - } if (data.action == "read") { this.htmltable.current_selection().removeClass("unseen"); } else { @@ -874,16 +851,13 @@ Webmail.prototype = { }, delete_callback: function(data) { - if (data.status == "ok") { - var msg = (data.respmsg) ? data.respmsg : gettext("Message deleted"); - this.go_back_to_listing(); - if (this.get_current_mailbox() != this.options.trash) { - $("a[name=totrash]").removeClass("disabled"); - } - $("body").notify("success", msg, 2000); - } else { - $("body").notify("error", data.respmsg); + var msg = (data.respmsg) ? data.respmsg : gettext("Message deleted"); + + this.go_back_to_listing(); + if (this.get_current_mailbox() != this.options.trash) { + $("a[name=totrash]").removeClass("disabled"); } + $("body").notify("success", msg, 2000); }, /* @@ -972,10 +946,9 @@ Webmail.prototype = { var $this = $(this); $.ajax({ - url: $this.attr("href"), - success: function() { - $this.parent().remove(); - } + url: $this.attr("href") + }).done(function() { + $this.parent().remove(); }); }, @@ -1069,18 +1042,13 @@ Webmail.prototype = { $.ajax({ url: plug.options.move_url, data: "msgset=" + selection.join() + "&to=" + to, - dataType: 'json', - success: function(data) { - if (data.status == "ok") { - if (unseen_cnt) { - plug.change_unseen_messages(from, -unseen_cnt); - plug.change_unseen_messages(to, unseen_cnt); - } - plug.listmailbox_callback(data); - } else { - $("body").notify("error", data.respmsg); - } + dataType: 'json' + }).done(function(data) { + if (unseen_cnt) { + plug.change_unseen_messages(from, -unseen_cnt); + plug.change_unseen_messages(to, unseen_cnt); } + plug.listmailbox_callback(data); }); } }); diff --git a/modoboa/extensions/webmail/views.py b/modoboa/extensions/webmail/views.py index 5291f8a7a..58e4c949b 100644 --- a/modoboa/extensions/webmail/views.py +++ b/modoboa/extensions/webmail/views.py @@ -12,8 +12,7 @@ from django.views.decorators.csrf import csrf_exempt from django.views.decorators.gzip import gzip_page from modoboa.lib import parameters from modoboa.lib.webutils import ( - _render_to_string, ajax_response, ajax_simple_response, - render_to_json_response + _render_to_string, ajax_response, render_to_json_response ) from modoboa.extensions.admin.lib import needs_mailbox from .exceptions import WebmailError @@ -23,7 +22,7 @@ from .lib import ( decode_payload, AttachmentUploadHandler, save_attachment, ImapListing, EmailSignature, clean_attachments, set_compose_session, send_mail, - ImapEmail + ImapEmail, ReplyModifier, ForwardModifier ) from templatetags import webmail_tags @@ -66,8 +65,7 @@ def move(request): mbc = get_imapconnector(request) mbc.move(request.GET["msgset"], request.session["mbox"], request.GET["to"]) resp = listmailbox(request, request.session["mbox"], update_session=False) - resp.update(status="ok") - return ajax_simple_response(resp) + return render_to_json_response(resp) @login_required @@ -85,8 +83,7 @@ def delete(request): message = ungettext("%(count)d message deleted", "%(count)d messages deleted", count) % {"count": count} - resp = dict(status="ok", respmsg=message) - return ajax_simple_response(resp) + return render_to_json_response(message) @login_required @@ -102,10 +99,10 @@ def mark(request, name): except AttributeError: raise WebmailError(_("Unknown action")) - return ajax_simple_response( - dict(status="ok", action=status, mbox=name, - unseen=imapc.unseen_messages(name)) - ) + return render_to_json_response({ + 'action': status, 'mbox': name, + 'unseen': imapc.unseen_messages(name) + }) @login_required @@ -115,9 +112,9 @@ def empty(request, name): raise WebmailError(_("Invalid request")) get_imapconnector(request).empty(name) content = "
%s
" % _("Empty mailbox") - return ajax_simple_response(dict( - status="ok", listing=content, mailbox=name - )) + return render_to_json_response({ + 'listing': content, 'mailbox': name + }) @login_required @@ -125,7 +122,7 @@ def empty(request, name): def compact(request, name): imapc = get_imapconnector(request) imapc.compact(name) - return ajax_simple_response(dict(status="ok")) + return render_to_json_response({}) @login_required @@ -484,7 +481,7 @@ def viewmail(request): def submailboxes(request): topmailbox = request.GET.get('topmailbox', '') mboxes = get_imapconnector(request).getmboxes(request.user, topmailbox) - return ajax_simple_response(dict(status="ok", mboxes=mboxes)) + return render_to_json_response(mboxes) @login_required @@ -498,7 +495,7 @@ def check_unseen_messages(request): imapc = get_imapconnector(request) for mb in mboxes: counters[mb] = imapc.unseen_messages(mb) - return ajax_simple_response(dict(status="ok", counters=counters)) + return render_to_json_response(counters) @login_required @@ -570,6 +567,8 @@ def index(request): pass response.update(callback=action) - if not "status" in response: - response.update(status="ok") - return ajax_simple_response(response) + http_status = 200 + if "status" in response: + del response['status'] + http_status = 400 + return render_to_json_response(response, status=http_status) diff --git a/modoboa/lib/webutils.py b/modoboa/lib/webutils.py index 7bbfbc136..8723b50c6 100644 --- a/modoboa/lib/webutils.py +++ b/modoboa/lib/webutils.py @@ -89,17 +89,6 @@ def ajax_response(request, status="ok", respmsg=None, return HttpResponse(simplejson.dumps(jsonctx), mimetype="application/json") -def ajax_simple_response(content, **response_kwargs): - """Simple AJAX response - - No extra formatting is done. The content is passed directly to simplejon. - - :param content: the response's content (list, dict, string) - """ - response_kwargs["content_type"] = "application/json" - return HttpResponse(simplejson.dumps(content), **response_kwargs) - - def render_to_json_response(context, **response_kwargs): """Simple shortcut to render a JSON response. diff --git a/modoboa/static/js/confirmation.js b/modoboa/static/js/confirmation.js index 3d6296be9..bf2fe35bd 100644 --- a/modoboa/static/js/confirmation.js +++ b/modoboa/static/js/confirmation.js @@ -89,7 +89,7 @@ }); $.ajax({ cache: false, - method: this.options.method, + type: this.options.method, data: params, url: this.$element.attr('href') }).done($.proxy(function(data) { @@ -98,15 +98,7 @@ return; } window.location.reload(); - }, this)).fail(function(jqxhr) { - var data; - try { - data = $.parseJSON(jqxhr.responseText); - } catch (e) { - data = gettext('Internal Error'); - } - $("body").notify("error", data); - }); + }, this)); this.box.remove(); } }; diff --git a/modoboa/static/js/creation_wizard.js b/modoboa/static/js/creation_wizard.js index a04e4bb82..e10985d64 100644 --- a/modoboa/static/js/creation_wizard.js +++ b/modoboa/static/js/creation_wizard.js @@ -38,41 +38,41 @@ var $form = (this.options.formid) ? $('#' + this.options.formid) : $('form'); var data = $form.serialize() + "&stepid=" + this.get_current_step_id(); - $.ajax({type: 'POST', url: $form.attr("action"), data: data}) - .done($.proxy(function(resp) { - if (!last) { - var stepid = resp.stepid + 1; - $('input:text:visible:first').focus(); - this.set_current_title(resp.title); - if (this.options.transition_callbacks[stepid] != undefined) { - this.options.transition_callbacks[stepid](); - } - this.$element.carousel('next'); + $.ajax({ + type: 'POST', url: $form.attr("action"), data: data, global: false + }).done($.proxy(function(resp) { + if (!last) { + var stepid = resp.stepid + 1; + $('input:text:visible:first').focus(); + this.set_current_title(resp.title); + if (this.options.transition_callbacks[stepid] != undefined) { + this.options.transition_callbacks[stepid](); + } + this.$element.carousel('next'); + } else { + $("#modalbox").modal('hide').remove(); + if (this.options.success_callback != undefined) { + this.options.success_callback(resp); } else { - $("#modalbox").modal('hide').remove(); - if (this.options.success_callback != undefined) { - this.options.success_callback(resp); - } else { - window.location.reload(); - } + window.location.reload(); } - }, this)) - .fail($.proxy(function(jqxhr) { - var resp = $.parseJSON(jqxhr.responseText); - if (resp.stepid != undefined) { - var stepid = resp.stepid; - display_form_errors("step" + stepid, resp); - if (this.options.error_callbacks[stepid] != undefined) { - this.options.error_callbacks[stepid](); - } - $('input:text:visible:first').focus(); - if (resp.respmsg) { - $(".modal-body").prepend(build_error_alert(resp.respmsg)); - } - return; + } + }, this)).fail($.proxy(function(jqxhr) { + var resp = $.parseJSON(jqxhr.responseText); + if (resp.stepid != undefined) { + var stepid = resp.stepid; + display_form_errors("step" + stepid, resp); + if (this.options.error_callbacks[stepid] != undefined) { + this.options.error_callbacks[stepid](); } - $(".modal-body").prepend(build_error_alert(resp)); - }, this)); + $('input:text:visible:first').focus(); + if (resp.respmsg) { + $(".modal-body").prepend(build_error_alert(resp.respmsg)); + } + return; + } + $(".modal-body").prepend(build_error_alert(resp)); + }, this)); }, update_buttons: function() { diff --git a/modoboa/static/js/global.js b/modoboa/static/js/global.js index 5b28f076b..b899731c0 100644 --- a/modoboa/static/js/global.js +++ b/modoboa/static/js/global.js @@ -31,7 +31,10 @@ function modalbox(e, css, defhref, defcb, defclosecb) { $(href).modal('open'); return; } - $.ajax({type: "GET", url: href}).done(function(data) { + $.ajax({ + type: "GET", + url: href + }).done(function(data) { if (typeof data === "object") { /* * Compatibility with the old way... @@ -70,9 +73,6 @@ function modalbox(e, css, defhref, defcb, defclosecb) { if (css != undefined) { $div.css(css); } - }).fail(function(jqxhr) { - var data = $.parseJSON(jqxhr.responseText); - $("body").notify("error", data); }); } @@ -168,6 +168,7 @@ function simple_ajax_form_post(e, options) { } $.ajax({ type: "POST", + global: false, url: $form.attr("action"), data: args }).done(function(data) { @@ -264,16 +265,11 @@ function simple_ajax_request(e, uoptions) { if (e != undefined) e.preventDefault(); $.ajax({ url: $this.attr("href"), - dataType: 'json', - success: function(data) { - if (data.status == "ok") { - if (options.ok_cb) options.ok_cb(data); - if (data.respmsg) { - $("body").notify("success", data.respmsg, 2000); - } - } else { - $("body").notify("error", data.respmsg); - } + dataType: 'json' + }).done(function(data) { + if (options.ok_cb) options.ok_cb(data); + if (data) { + $("body").notify("success", data, 2000); } }); } @@ -304,8 +300,21 @@ function activate_widget(e) { } } +/* + * Default error handler for AJAX requests. + */ +function default_ajax_error_handler(event, jqxhr, settings) { + try { + var data = $.parseJSON(jqxhr.responseText); + } catch (x) { + var data = gettext("Internal error"); + } + $('body').notify('error', data); +} + $(document).ready(function() { $(document).ajaxSuccess(function(e, xhr, settings) { ajax_login_redirect(xhr); }); + $(document).ajaxError(default_ajax_error_handler); $(document).on('click', 'a[data-toggle="ajaxmodal"]', modalbox); $(document).on('click', 'a[data-toggle="ajaxmodal-autowidth"]', modalbox_autowidth); $(document).on('click', '.activator', activate_widget); diff --git a/modoboa/static/js/history.js b/modoboa/static/js/history.js index d582219a1..2d21dca4f 100644 --- a/modoboa/static/js/history.js +++ b/modoboa/static/js/history.js @@ -227,20 +227,14 @@ History.prototype = { $.ajax({ url: this.serialized, cache: false, - complete: $.proxy(function(XMLHttpRequest, textStatus) { - var resp; - try { - resp = $.parseJSON(XMLHttpRequest.responseText); - } catch (e) { - resp = { status: 'ko', respmsg: gettext('Internal Error') }; - } - if (resp.status == "ko") { - $("body").notify("error", resp.respmsg); - return; - } - var callback = (resp.callback != undefined) ? resp.callback : "default"; - this.callbacks[callback](resp); - }, this) - }); + dataType: 'json' + }).done($.proxy(function(resp) { + var callback = (resp.callback != undefined) ? resp.callback : "default"; + + this.callbacks[callback](resp); + if (resp.respmsg) { + $("body").notify("success", resp.respmsg, 2000); + } + }, this)); } }; \ No newline at end of file diff --git a/modoboa/static/js/poller.js b/modoboa/static/js/poller.js index 7beba47ea..acca1c4e5 100644 --- a/modoboa/static/js/poller.js +++ b/modoboa/static/js/poller.js @@ -62,19 +62,18 @@ Poller.prototype = { $.ajax({ url: this.url + args, dataType: 'json', - success: function(data) { - poller.running_request = false; - if (data.status == "ok") { - if (poller.options.success_cb) { - poller.options.success_cb(data); - } - poller.reset(); - } else { - $("body").notify("error", data.respmsg); - if (poller.options.error_cb) { - poller.options.error_cb(data); - } - } + global: false + }).done(function(data) { + poller.running_request = false; + if (poller.options.success_cb) { + poller.options.success_cb(data); + } + poller.reset(); + }).fail(function(jqxhr) { + var data = $.parseJSON(jqxhr.responseText); + $("body").notify("error", data); + if (poller.options.error_cb) { + poller.options.error_cb(data); } }); }