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.

2 Answers 2

3

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

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

2 Comments

Ok thank you! I am getting a CSRF verification failed 403 error.I have already added the javascript snippet. link
You'll need to either pass the CSRF token to the JavaScript via {% csrf_token %} or use one of the CSRF decorators to modify the CSRF handling on the view.
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();
    }

Comments

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.