Reputation: 429
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.
Upvotes: 0
Views: 4338
Reputation: 1043
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();
}
Upvotes: 0
Reputation: 799490
You don't need jQuery for this. Create a form that performs a POST to the appropriate URL and submit it.
Upvotes: 3