I'm trying to render a form through javascript in django. I tried inserting the csrf token tag through the ways described in stack overflow post How do I include Django 1.2's CSRF token in a Javascript-generated HTML form? but it did not work for me :/ I've been trying for hours to find out the reason!
var CSRF_TOKEN = document.getElementById('csrf_token').value;
for (i = 0; i < this.ShoeList.length; i++) {
html += "<form method='POST' action='/AddToCart/'>'"+CSRF_TOKEN+"'<div class = 'box'<li><img src=' " + this.ShoeList[i].imageSource + "'/>";
}
and this is my template code:
<body onload="start()">
<input id="csrf_token" value="{{ csrf_token }}"/>
</body>
The token value is being displayed correctly when i run the code. But it does not accept the token for some reason. Please help!
for (i = 0; i < this.ShoeList.length; i++) {
html += "<form method='POST' action='/AddToCart/'>{% csrf_token %}<div class = 'box'<li><img src=' " + this.ShoeList[i].imageSource + "'/>";
}
var CSRF_TOKEN = document.getElementById('csrf_token').value;
for (i = 0; i < this.ShoeList.length; i++) {
html += "<form method='POST' action='/AddToCart/'><input type='hidden' value='"+CSRF_TOKEN+"' name='csrfmiddlewaretoken'><div class = 'box'<li><img src=' " + this.ShoeList[i].imageSource + "'/>";
}
Related
function getNews() {
fetch(
"https://cors-anywhere.herokuapp.com/http://newsapi.org/v2/top-headlines?country=india&apiKey=<MyApiKey>",
{ headers: new Headers({ "X-Requested-With": "abcd" }) }
)
.then((a) => a.json())
.then((response) => {
for (var i = 0; i < response.articles.length; i++) {
document.getElementById("output").innerHTML +=
"<div class='article' style='padding-top:20px;'> <img class='image' style='float:left; width:150px;' src='" +
response.articles[i].urlToImage +
"' > <h1>" +
response.articles[i].title +
"</h1>" +
response.articles[i].source.name +
"<br>" +
response.articles[i].description +
" <a href='" +
response.articles[i].url +
"'target='_blank'>" +
response.articles[i].url +
"</a></div>";
}
});
}
My console doesn't show any errors now, but onclick getNews() does not display anything!!
<body>
<button class="btn" onclick="getNews()">Get News Here.</button>
<div id="output"></div>
<script src="index.js"></script>
</body>
I was hoping to display the news by this api, (I tried to use 'in' as my country code but didn't work).
https://www.youtube.com/watch?v=yY0ciWj8oco&t=24s - I was trying to implement it by this video since yesterday, fixed some errors I got but right now I have no errors in console nor on my window after I click on 'get news here' button, it does nothing!! Please help!!
This question already has answers here:
JavaScript post request like a form submit
(32 answers)
Closed 7 years ago.
Basically what I want to do is send POST data when I change the window.location, as if a user has submitted a form and it went to a new page. I need to do it this way because I need to pass along a hidden URL, and I can’t simply place it in the URL as a GET for cosmetic reasons.
This is what I have at the moment, but it doesn’t send any POST data.
if(user has not voted) {
window.location = 'http://example.com/vote/' + Username;
}
I know that you can send POST data with jQuery.post(), but I need it to be sent with the new window.location.
So to recap, I need to send api_url value via POST to http://example.com/vote/, while sending the user to the same page at the same time.
For future reference, I ended up doing the following:
if(user has not voted) {
$('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');
document.forms['vote'].submit();
}
per #Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
Construct and fill out a hidden method=POST action="http://example.com/vote" form and submit it, rather than using window.location at all.
Here's a simple small function that can be applied anywhere as long as you're using jQuery.
var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});
// jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
value = value.split('"').join('\"')
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
Here is a method, which does not use jQuery.
I used it to create a bookmarklet, which checks the current page on w3-html-validator.
var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';
var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you are using jQuery, there is a redirect plugin that works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Note: You can pass the method types GET or POST as an optional third parameter; POST is the default.
The answers here can be confusing so i will give you a sample code that i am working with.
To start with note that there is no POST parameter to java script windows.location function that you are referring to.
So you have to...
Dynamically make a form with a POST parameter.
Dynamically put a textbox or textboxes with your desired values to post
Invoke the submit form you dynamically created.
And for the example.
//---------- make sure to link to your jQuery library ----//
<script type="text/javascript" >
var form = $(document.createElement('form'));
$(form).attr("action", "test2.php");
$(form).attr("method", "POST");
$(form).css("display", "none");
var input_employee_name = $("<input>")
.attr("type", "text")
.attr("name", "employee_name")
.val("Peter" );
$(form).append($(input_employee_name));
var input_salary = $("<input>")
.attr("type", "text")
.attr("name", "salary")
.val("1000" );
$(form).append($(input_salary));
form.appendTo( document.body );
$(form).submit();
</script>
If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.
On test2.php you can get your values thus.
$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];
Needless to say , make sure you sanitize your passed values.
Generic function to post any JavaScript object to the given URL.
function postAndRedirect(url, postData)
{
var postFormStr = "<form method='POST' action='" + url + "'>\n";
for (var key in postData)
{
if (postData.hasOwnProperty(key))
{
postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
}
}
postFormStr += "</form>";
var formElement = $(postFormStr);
$('body').append(formElement);
$(formElement).submit();
}
This is quite handy to use:
var myRedirect = function(redirectUrl, arg, value) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
$('body').append(form);
$(form).submit();
};
then use it like:
myRedirect("/yourRedirectingUrl", "arg", "argValue");
var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};
Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/
Going to try this and other suggestions for my work.
Is there any other way to do the same ?
You can use target attribute to send form with redirect from iframe.
Your form open tag would be something like this:
method="post" action="http://some.url.com/form_action" target="_top"
SOLUTION NO. 1
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id='"+product_id+"'");
SOLUTION NO. 2
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);
details
I am using ccavenue npm module to integrate payment gateway in my website.
The problem with that modules is that it uses res.write and res.writehead while the res variable passed to the module is generated by hapi and thus generating a error. So, what is the hapi equivalent of res.writehead and res.write.
Here is my hapi code:
var ccavenue = require('ccavenue');
ccavenue.setMerchant("******");
ccavenue.setWorkingKey("*******************");
ccavenue.setRedirectUrl("/redirect-url");
module.exports = function(plugin, options, next) {
plugin.route({
method: 'GET',
path: '/checkout',
handler: function(request, reply) {
var param = {
billing_cust_address: 'Bangalore',
billing_cust_name: 'Nitish Kumar'
};
ccavenue.setOrderId("8981455644");
ccavenue.setOrderAmount("1000");
ccavenue.setOtherParams(param);
ccavenue.makePayment(reply);
}
});
}
This is the module function:
function makePayment(res) {
var errors = helper.checkRequiredField(config);
if(errors.length > 0) {
throw new Error(errors);
}
var Checksum = helper.getCheckSum(config.merchantId, config.orderAmount, config.orderId, config.redirectUrl, config.workingKey); //This function is to verify
var body = "<form method='post' name='checkout' id='checkout' action='https://www.ccavenue.com/shopzone/cc_details.jsp'>" +
"<input type=hidden name='Merchant_Id' value='" + config.merchantId + "'>" +
"<input type=hidden name='Amount' value='" + config.orderAmount + "'>" +
"<input type=hidden name='Order_Id' value='" + config.orderId + "'>" +
"<input type=hidden name='Redirect_Url' value='" + config.redirectUrl +"'>" +
"<input type=hidden name='Checksum' value='" + Checksum + "'>" +
"<input type=hidden name='TxnType' value='A'>" +
"<input type=hidden name='ActionID' value='TXN'>";
for(var key in otherParams) {
body += "<input type=hidden name='"+ key +"' value='" + otherParams[key] + "'>";
}
body += "</form><script type='text/javascript'>" +
"document.getElementById('checkout').submit();" +
"</script>";
res.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/html'
});
res.write(body);
res.end();
}
This is the error:
Debug: internal, implementation, error
TypeError: Uncaught error: res.writeHead is not a function
at Object.makePayment (/home/satnam-sandhu/Workstation/cuboid.io/servers/web/node_modules/ccavenue/index.js:59:8)
at Object.plugin.route.handler (/home/satnam-sandhu/Workstation/cuboid.io/servers/web/ccavenue/index.js:21:15)
at Object.exports.execute.internals.prerequisites.internals.handler.finalize [as handler] (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/handler.js:101:51)
at /home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/handler.js:32:23
at internals.Protect.run.finish [as run] (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/protect.js:60:12)
at exports.execute.finalize (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/handler.js:26:22)
at each (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/request.js:401:16)
at iterate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:36:13)
at done (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:28:25)
at internals.Auth.test.internals.Auth._authenticate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/auth.js:222:16)
at internals.Auth.test.internals.Auth.authenticate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/auth.js:197:17)
at each (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/request.js:401:16)
at iterate (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:36:13)
at done (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/items/lib/index.js:28:25)
at /home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/lib/protect.js:50:16
at wrapped (/home/satnam-sandhu/Workstation/cuboid.io/node_modules/hapi/node_modules/hoek/lib/index.js:875:20)
I assume you are using an older version of hapi 17.0.0, in order to to reply with html use https://github.com/hapijs/vision. Also this example tutorial should help
https://futurestud.io/tutorials/hapi-how-to-render-views. Hapi will do most of the work for you. If you want to use node's res and req http server objects you need to expose the raw request and response objects from hapi's internals as documented here https://hapijs.com/api/16.5.2#request-properties under raw property.
i'm trying to add to the html page a form with js (like the html token {% csrf_token %} when loading the page does):
table += "<td><form action='' method='post'>";
table += "<input type='submit' value='Delete?' />";
table += "</form></td>;
$("#tbody").append(table);
my problem is that i get a csrf validation error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
i tried to add a custom csrf token:
var buf = new Uint8Array(1);
window.crypto.getRandomValues(buf);
table += "<input type='hidden' name='csrfmiddlewaretoken' value='" + buf[0] + "'>";
but i still get an error.
i also have in my js file the following code (which i got from the django website - and i don't know how it actually works..):
//enable csrf post ajax
//This function gets cookie with a given name
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;
}
var csrftoken = getCookie('csrftoken');
/*
The functions below will create a header with csrftoken
*/
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain &&
(!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url)))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
is there a way to add a csrf token with js the way i tried or it can not be?
The Javascript code provided by django for csrftoken extraction assigns csrftoken value to a variable named csrftoken
You can access it anywhere by its variable name, like this:
table += "<input type='hidden' name='csrfmiddlewaretoken' value='" + csrftoken + "'>";
Make sure you've included the js provided by django in your page before accessing csrftoken
Also, as #Sander pointed out, if you're using inline JS you can directly use csrf_token template tag instead.
table += "{% csrf_token %}";
Is the js added as inline js to your django template?
In that case you can do:
table += "<td><form action='' method='post'>";
table += "{% csrf_token %}";
table += "<input type='submit' value='Delete?' />";
table += "</form></td>;
$("#tbody").append(table);
I am trying to make an image take a value in as a source, after the image tag (and a related radio button) has been created using JavaScript. I have discerned the following from testing and alert outputs:
If the image src is provided at the creation of the image tag using an exact filepath, it will show the image correctly (e.g. src='images/0.jpg'). However, this is not helpful since I need it to work for any given image, not a specific one.
If the image src is provided at the creation of the image tag using a variable containing a filepath, it fails to generate the image tag or the radio button at all (e.g. src='" + result + '").
NOTE: The last example is not present in the code below. The result was found by moving the '$.post' section to the line directly under the 'out +=' line within the for loop.
If the image src is left blank at the creation of the image tag, the image tag and radio button are created, though the image is blank as expected. If I then try to use 'getElementByID(imgID).src' to change the image source after this, it fails to do anything. ('imgID' here is an example, not what the code says).
On top of the above, using alerts and dumping info into divs indicate that the comicID is being correctly posted, and the filepath of the image src is definitely being found, and is being copied into the variable 'result' correctly, even one line before the creation of the tag or the attempt to edit it using 'getElementById'.
At this point I'm stumped, I don't know what could logically be stopping the src from reading in.
--
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
tempID = (arr[j].comicID);
$.post("getCover.php", {comicID:tempID}, function(result)
{
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
);
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print_r($row["pageLocation"]);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
To my knowledge, loadList.php is working perfectly, so I didn't list its code to keep things relevant.
I copied your code and tweaked it a little so I could run it without the web services and it works great. Here is the HTML page I created:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
// JSON parsing for 'loadComic'.
function loadComicJSON()
{
var arr = [{comicID: 1},{comicID: 2},{comicID: 3}];
var result = "monkey.jpeg";
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
var imgSrc;
tempID = (arr[j].comicID);
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
}
}
</script>
</head>
<body>
<div id="loadList"></div>
<button onclick="loadComicJSON()">Try it</button>
</body>
</html>
As you can see, I created an array of JSON objects that hold the comicID and am statically creating the image as 'monkey.jpeg'.
The code works so there is either an issue with the 'response' that you pass into your loadComicJSON method or the result from your POST method.
Add a couple of console.log statements and look at the two values I mentioned and you will likely see the issue.
Solved the issue myself. It turned out that the $.post needed to be $.get and that it needed to technically be outside of a loop (i.e. in its own function) to work properly. Works fine now after that and a couple minor tweaks.