I have a very basic Django view that, once it receives a request, should send a response to the page that the user is visiting, so that i can display a message on that page, without having to refresh the page.
Here is my view:
def Action(request):
response = ''
if request.method == 'POST':
if request.POST.get('ajaxform', False) == 'submit':
data = request.POST.get('formdata', False)
mymodel = Userdata()
mymodel.save()
response = 'Submitted!'
return HttpResponse(json.dumps(response), content_type='application/json')
Basically, when a POST request is received, this view should send a JSON response to the template with the message Submitted
.
This view works, when i'm browsing my template, on my Dev tools i can see the JSON response Submitted
being received by the page, but i don't understand how can i show it using Jquery.
Can someone point me out on how could i create a Jquery function that is triggered only when a Json response is received by a Django view?
Basically, in this case, when the Django view fires the response Submitted
, my Jquery function should receive that message and do some stuff with it.
I tried this:
$.ajax({
url: "/mytemplate/Action",
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data)
}
});
The problem with this function, though, is that nothing is being printed in my console, although i can see the response on my Network tab.
My guess would be that, since you are calling the json.dumps in a string, your jQuery is also receiving a string. Maybe try calling json.dumps({'response': 'Submitted!') in your view.
An easier solution may be to use the ".done" callback, which is triggered after the post request is successful. This way, you won't need a specific response from the python view. Doing this, a simple HttpResponse('true') should work.
More specifics about the .done callback here: https://api.jquery.com/jquery.get/
Edit after clarification
The first problem is in your view. There, you specified
if request.method == 'POST':
but your ajax request is using the GET method
type: 'get',
Besides that, you still sending a string response, and not an 'stringfied' dictionary.
I made an working example similar to your post. IMO, your view should be:
def Action(request):
response = ''
if request.method == 'POST':
if request.POST.get('ajaxform', False) == 'submit':
data = request.POST.get('formdata', False)
mymodel = Userdata()
mymodel.save()
response = 'Submitted!'
return JsonResponse({'resp': response})
For making the request and dealing with the response, I made a $.post, which is more concise
$.post("/mytemplate/Action",
params,
function( data )
{
console.log(data )
}
)