0

I am wanting to send data over to my Django view and at the same time redirect the page. So, I think ajax is out the window.I am unsure how to do this via Jquery.

Zach
  • 399
  • 1
  • 6
  • 17

2 Answers2

3

You don't need jQuery for this. Create a form that performs a POST to the appropriate URL and submit it.

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
  • Ok thank you! I am getting a CSRF verification failed 403 error.I have already added the javascript snippet. [link](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax) – Zach Mar 25 '12 at 21:26
  • 1
    You'll need to either pass the CSRF token to the JavaScript via `{% csrf_token %}` or use one of the [CSRF decorators](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#utilities) to modify the CSRF handling on the view. – Ignacio Vazquez-Abrams Mar 25 '12 at 21:28
0

Here's my code for sending data via POST to a Django server. I visted the site Ignacio suggested and also added csrf so it will work with typical Djano views.

    // get cookie using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }


    function post_to_url(path, params, method) {
        method = method || "post"; // Set method to post by default if not specified.

        // The rest of this code assumes you are not using a library.
        // It can be made less wordy if you use one.
        var form = document.createElement("form");
        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var key in params) {
            if(params.hasOwnProperty(key)) {
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden");
                hiddenField.setAttribute("name", key);
                hiddenField.setAttribute("value", params[key]);

                form.appendChild(hiddenField);
             }
        }

        csrfField = document.createElement("input");
        var csrftoken = getCookie('csrftoken')
        console.log("token" + csrftoken)
        csrfField.setAttribute("type", "hidden");
        csrfField.setAttribute("name", "csrfmiddlewaretoken");
        csrfField.setAttribute("value", csrftoken)
        form.appendChild(csrfField)

        document.body.appendChild(form);
        form.submit();
    }
Rick Giuly
  • 773
  • 1
  • 10
  • 15