Created
February 7, 2012 14:13
-
-
Save gileno/1759872 to your computer and use it in GitHub Desktop.
Ajax com serialize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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 | |
} | |
} | |
}); | |
}); | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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