Reputation: 798
I am trying to make a simple POST request to a server using Django. I can make the post call using another api client just to test it, but when using jquery it never return anything or shows the alert from the callback function. Below are my jquery and django code. I've replaced the api call but I know that it is correct.
$(document).ready(function(){
$("#signInSubmit").click(function(){
alert("Posting email: "+$("#email").val()+" guests: "+$("#guests").val());
$.post("apicall",
{
'email':$("#email").val(),
'guests':$("#guests").val(),
'event':"1"
},
function(data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
And this is the django view getting hit:
@csrf_exempt
def participant_info(request):
if request.method == 'GET':
participant_email = request.GET.get('email')
participant = Participant.objects.get(email = participant_email)
#serialized_obj = serializers.serialize('json', [ participant, ])
response = HttpResponse()
response.content = serialized_obj = serializers.serialize('json', [ participant, ])
response['Content-Type'] = 'application/json'
return response
#return HttpResponse(response, mimetype="application/json")
if request.method == 'POST':
participant_email = request.POST.get('email', '')
numguests = request.POST.get('guests', '')
eventid = request.POST.get('event', '')
participantkey = Participant.objects.get(email = participant_email)
eventkey = Event.objects.get(id=eventid)
per = Participant_Event_Record(guests = numguests, event = eventkey, participant = participantkey)
per.save()
response = HttpResponse()
response.content = serialized_obj = serializers.serialize('json', [ per, ])
response['Content-Type'] = 'application/json'
return response
Upvotes: 0
Views: 204
Reputation: 798
Turns out it was wrapped in a form within the body of the HTML that I had not noticed. After removing the form wrapper it worked perfectly.
Upvotes: 0
Reputation: 2086
Could be a couple things going on I think:
Specify the content type in the jQuery call, make sure it says 'appliciation/json' (http://api.jquery.com/jQuery.ajax/) since you're serializing assuming it's JSON but it defaults to 'application/x-www-form-urlencoded'.
Your POST url expects a / at the end of its URL, and you're posting to an endpoint without a /, which makes Django issue a redirect to the / URL. You can disable that by setting the APPEND_SLASH setting (https://docs.djangoproject.com/en/1.4/ref/settings/#append-slash), but really it's best to always call all endpoints with '/' at the end, so I'd say instead of posting with $.post("apicall", ...), try $.post("apicall/", ...) and see if that helps.
Otherwise, can you post the error that you get when you do try? both from the Django console and the Javascript console in Chrome?
Upvotes: 1