Skip to content

Instantly share code, notes, and snippets.

@gileno
Created February 7, 2012 14:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gileno/1759872 to your computer and use it in GitHub Desktop.
Save gileno/1759872 to your computer and use it in GitHub Desktop.
Ajax com serialize
$(function() {
$("#meu-form").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
$.ajax( {
url: "minha-url",
type: "post",
data: data,
dataType: "json",
success: function(json) {
if(json.success) {
// faz alguma coisa ai
} else {
// mostra um alert ou algo do tipo
// você pode enviar na resposta http no servidor um campo a mais no json que é a mensagem de erro
}
}
});
});
);
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.utils import simplejson
from forms import MeuForm
def minha_view(request):
success = False
if request.method == 'POST':
form = MeuForm(data=request.POST)
if form.is_valid():
# ai tu faz o que tu quiser
success = True
message = u"Ação realizada com sucesso"
else:
# aqui você vai ter os erros do form
# é legal tu fazer alguma forma para jogá-los na variável message para no js exibir esses erros
# compactados
message = u"Deu merda no form ajeito isso ai"
else:
message = u"Método não permitido"
json = {"success": success, "message": message}
json = simplejson.dumps(json, ensure_ascii=False)
return HttpResponse(json, mimetype="text/javascript")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment