0

return render(request, 'index.html', {"flag": flag, "form": form})

I want to pass flag value which should be read by javascript to change style of an element in template, but since rendering it again the flag value is lost and set back to "none" ,is there any way to not use render and pass the variable to a url where the page is already rendered

 $.ajax({
            type: "GET",
            url: "/home", //url of site no need to enter full site
           dataType: "json",


            contentType: 'application/json',

            success: function (response) {
             
                  alert(response.flag);

// Gives value of flag
            },

            error: function (response) {
               alert('error');
            }
        });

update : i tried this code but it always goes into error session and doesnt get into success block

1
  • What do you mean by rendering it again? does it mean reloading the page? Commented Jun 28, 2022 at 1:16

1 Answer 1

1
In your javascript file use ajax method to call your views.py, 

   $.ajax({
            type: "GET", method GET or POST
            url: "/url_name/", //url of site no need to enter full site

            data: {
                'key': value, // data you want to pass if any
            },

            contentType: 'application/json',

            success: function (response) {
                  console.log(response.flag) // Gives value of flag  
            },

            error: function (data) {
                console.log('error');
            }
        });;

In your views.py you can pass your flag value as JSON response,

    def view_name(response):
        return JsonResponse({'flag': flag }, content_type='application/json')
Sign up to request clarification or add additional context in comments.

2 Comments

i tried this but couldnt get it working, i am passing flag="accept"/flag="reject" as {"flag": flag}
def view_name(request): # Use request instead of response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.