0

I am trying to send a json response from django view to template but when I try to console.log the response in my ajax, I am getting nothing. What could i be doing wrong ? I am trying to pass the result data from views to my ajax success function. I also noticed something strange that when I mention the datatype = json in my ajax then I dont receive any response in the success function but when I remove the dataType = json then I get the entire html of my template in my success function as a response. Why is that ??

   views.py
    class ChangePassword(View):
        def post(self, request, *args, **kwargs):
            form = PasswordChangeForm(request.POST)

            #current_password = json.loads(get_value.current_password)
            #print ('current password',get_value['current_password'])

            if form.is_valid():
                print("valid form")
                user = CustomUser.objects.get(email=request.user.email)
                current_password = form.cleaned_data['current_password']
                print('current_password',current_password)

                new_password = form.cleaned_data['new_password']
                print('newpassword',new_password)

                if user.check_password(current_password):
                    print('entered')
                    update_session_auth_hash(self.request, self.request.user)  # Important!
                    user.set_password(new_password)
                    user.save()
                    result = {'success': "Succefully reset your password"};

                    result = json.dumps(result)
                    print ('result',result)


                    return render(request, 'change_password.html',context={'result': result})

                else:
                    return render(request, 'change_password.html', {'error': "We were unable to match you old password"
                                                                " with the one we have. <br>"
                                                                "Please ensure you are entering your correct password"
                                                                "then try again."})
            else:
                print("not valid")
                return render(request, 'change_password.html', {'form':form})

        def get(self, request, *args, **kwargs):
            return render(request, 'change_password.html', {})

template
  function changePassword() {
            csrfSetUP()
            new_pass = document.getElementById('new_pass')
            cur_pass = document.getElementById('current_pass')
            if (validpassword(new_pass) && cur_pass!= "") {
                var cpass = $('#current_password').val();
                var npass = $('#new_pass').val();
                var data = {current_password:cpass,new_password:npass}



                 $.ajax({
                        url: '/account/change_password/',
                        type: 'post',
                        data: data,
                        dataType: "json",

                        success: function(json) {
                            console.log(json)
                        }
                    });







            } else {
                $('#change_password').submit()
            }

        }
jassy
  • 71
  • 1
  • 1
  • 7

1 Answers1

1

When you are working with AJAX you have to use JSONResponse() instead of render()

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

If you need to have generated some HTML with that JSON - it is even better to use render_to_string method and return a html string to your AJAX, smth like that:

html = render_to_string('ajax/product_details.html', {"most_visited": most_visited_prods}) return HttpResponse(html)

NOTE: When using render_to_string remember to delete dataType: "json" from your AJAX, cuz u return not JSON, but a string.

P.S. Under this question there are plenty of examples how this can be done, but look at newer ones.

Chiefir
  • 2,561
  • 1
  • 27
  • 46