1

my question is, what´s the better way to pass a value from a javascript function to django view.

I have a template where I get a value through a javascript function, and I want to pass that value to a django view.

2 Answers 2

3

The question is pretty general, but here's one way of doing it. You could use jQuery to make your AJAX call like this:

        $.ajax({type: 'POST',
                url: '/fetch_data/',                            // some data url
                data: {param: 'hello', another_param: 5},       // some params  
                success: function (response) {                  // callback
                    if (response.result === 'OK') {
                        if (response.data && typeof(response.data) === 'object') {
                            // do something with the successful response.data
                            // e.g. response.data can be a JSON object
                        }
                    } else {
                        // handle an unsuccessful response
                    }
                }
               });

And your Django view would be something like this:

def fetch_data(request):
    if request.is_ajax():
        # extract your params (also, remember to validate them)
        param = request.POST.get('param', None)
        another_param = request.POST.get('another param', None)

        # construct your JSON response by calling a data method from elsewhere
        items, summary = build_my_response(param, another_param)

        return JsonResponse({'result': 'OK', 'data': {'items': items, 'summary': summary}})
    return HttpResponseBadRequest()

Many details are obviously omitted here, but you can use this as a guideline.

Sign up to request clarification or add additional context in comments.

Comments

1

Two ways here:

  1. Ajax request to your view
  2. Redirect user to new URL where your value is query parametr

2 Comments

have you any example of using ajax please? i´m new
@Jmint: That is outwith the scope of this question (and this site to be honest). If you're familiar with jquery, start at sitepoint.com/ajax-jquery for learning jquery AJAX. Google will help you find tutorials for AJAX with vanilla javascript

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.