1

I am using Ajax to convert my form data to JSON and sending it to my Django view. After successful processing I am returning a template response with some context data which I am not able to refer back in my HTML. I am stuck getting this to work. Any help would be really appreciated. Below is my HTML code and my Django view.

View:

class CustomerAttributeView(View):
    """
    Saves the attribute details for a user.
    Updates if already present
    """
    page = 'customer_attributes.html'

    def get(self, request):
        return render(request, self.page)

    def post(self, request):

        try:
            user = User.objects.get(id=request.session['user_id'])
            data = json.loads(request.POST.get('data'))

            attribute_ids_mapped_to_customer = CustomerAttributeMapping.objects.\
                filter(consuming_app_id=user.consuming_app_id).values_list('id', flat=True)

            #If no attributes mapped to the user then create and return
            if not attribute_ids_mapped_to_customer:
                insert_or_update_customer_attributes(user, data)
                context_data = {
                    'success_msg': 'Attribute details saved successfully'
                }
                return TemplateResponse(request, self.page, context=context_data)
        except Exception as e:
            logging.error("Error: " + str(e))
            context_data = {
                'error_msg': 'Error in saving customer attributes',
                'status_code': 400
            }
            return TemplateResponse(request, self.page, context=context_data)

AJAX:

$.ajax({
            url : "customer_attribute/", // the endpoint
            type : "POST", // http method
            data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
    });

URLs:

urlpatterns = [
    url(r'^customer_attribute/',csrf_exempt(CustomerAttributeView.as_view())),
]

My HTML code where I am trying to refer the context data I am returning from the view:

<span class="success-msg" id="success_msg">{% if success_msg %}{{ success_msg }}{% else %} {{""}} {% endif %}</span>
<span class="error" id="error_msg">{% if error_msg %}{{ error_msg }}{% else %} {{""}} {% endif %}</span>

I don't see either the success_msg nor the error_msg in my HTML. Is there anything I am doing wrong here?

viam0Zah
  • 25,949
  • 8
  • 77
  • 100
abhi1489
  • 187
  • 4
  • 14
  • 1
    Templates are rendered by Django _before_ they're sent to the browser. You cannot do anything with a django template once you're executing javascript. – thebjorn Jun 29 '20 at 16:48

2 Answers2

2

You're initiating an Ajax request but you're never catching its response. You should define a response handler in your JavaScript code. I assume that you use jQuery's $.ajax(). The following code will inject the response as it is to a container with ID reponse.

const xhr = $.ajax({
    url : "customer_attribute/", // the endpoint
    type : "POST", // http method
    data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
});

xhr.done(function (response) {
    $('#response').html(response)
});

However I guess customer_attributes.html is a template for the whole page. Probably that you don't want to be included again in itself. You might want to create a seperate HTML template that only renders the snippet you want to return on success.

If you want a more sophisticated way of handling the response data, you might want your Django view that instead of the HTML output it returns a JSON formatted data that you can better process in the client side (see Django's JsonResponse).

In general for the future, I recommend to use your web browser's developer toolbox to debug such issues, it should have a network inspector tool. As you perform the Ajax request, you should see a request going to your backend with all the request data -- and there you should also observe the response the backend gives to you. This way you can confirm if the backend gave the response as you expected in the first place.

viam0Zah
  • 25,949
  • 8
  • 77
  • 100
0

You didn't specify a success callback

$.ajax({
            url : "customer_attribute/", // the endpoint
            type : "POST", // http method
            data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
            success: (response) => {// do logic 

   }
    });

ref

Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30