Send HTTP Post request to a server with a specified CSRF token - javascript

Explanation:
I am trying to create a CSRF POC, but the problem is that a CSRF-token is required on www.example.com in order to prevent CSRF attacks.
Luckily, I managed to create a CSRF-Token that is always valid; lets say "abcdef". So now I can create a working CSRF POC if only I could send the CSRF-Token with it.
Is this possible with for instance AJAX? I searched for half an hour but couldn't find any answers on this, but that's on me I guess.
This is my POC until now:
<form action="http://www.example.com/change-mail" method="post">
<input type="submit">
<input type="hidden" name="email" value="newemail#gmail.com">
<!-- TODO: Send the CSRF-Token "abcdef" with it too! -->
</form>
Help is appreciated.
Edit #Daniƫl
Would something like this work?
HTML Part:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Email</b><br><br>
<form id="email">
<label for="email"> Email : </label>
<input type="text" id="email" />
<br><br>
<input type="button" id="email" value="email"/>
</form>
</body>
</html>
Javascript PART:
<script>
window.addEventListener('DOMContentLoaded', function() {
var email = document.querySelector('input#email');
email.addEventListener('click', function() {
var emailStr = email.value,
url="http://www.example.com/change-mail";
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.setRequestHeader('X-CSRF-Token', abcdef);
xmlHttpReq.send("email="+emailStr);
</script>
Thanks in advance, do I have to handle the response too?
Right now, when I hit the email button, nothing happens when I log the HTTP requests... too bad.

There are a number of issues with your current code, I have corrected it below.
window.addEventListener('DOMContentLoaded', function() {
var email = document.querySelector('input#submit');
email.addEventListener('click', function() {
var emailStr = email.value,
url="http://www.example.com/change-mail";
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.setRequestHeader('X-CSRF-Token', 'abcdef');
xmlHttpReq.send("email="+emailStr);
});
});
<!DOCTYPE html>
<html>
<body>
<b>Email</b><br><br>
<form id="emailform">
<label for="email"> Email : </label>
<input type="text" id="email" />
<br><br>
<input type="button" id="submit" value="email"/>
</form>
</body>
</html>
ORIGINAL ANSWER:
You can add a header to your XMLHttpRequest (ajax) call:
xhr.setRequestHeader('X-CSRF-Token', csrf_token);

Related

Form submit Ajax - vanilla js - JSON string instead element message

After submitting the form, I want to display success or error message by removing element id (id value display:none). Element contains the message text.
I can submit the form with this script, but instead showing me the element, new page is opened with JSON string.
What should be corrected in the script?
vanilla Javascript
<script type="text/javascript">
var form = document.getElementById("leadcontact");
var sent = document.getElementById('sent');
var notsent = document.getElementById('notsent');
form.onsubmit = function(event) {
event.preventDefault();
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", form.action, true);
xhr.send(formData);
xhr.onload = function(e) {
if (xhr.status === 200) {
sent.removeAttribute('id');
form.reset();
} else {
notsent.removeAttribute('id');
}
};
};
</script>
the Form
<form id="leadcontact" action="xxxxxxxxxxx" method="POST" enctype="multipart/form-data">
<div class="form-field-container">
<label for="name">name</label>
<input type="text" name="name">
</div>
<div class="form-field-container">
<label for="tel">phone</label>
<input type="text" name="phone">
</div>
<div class="form-field-container">
<label for="email">email</label>
<input type="email" name="email">
</div>
<div class="form-field-container">
<label for="message">message</label>
<textarea name="message"></textarea>
</div>
<p id="notsent" class="message-status error">Error! Not sent</p>
<p id="sent" class="message-status success">Message sent</p>
<button type="submit">Send</button>
</form>
JSON output page - the page shows after submission
{"success":true,"given_params":{"name":"","phone":"","email":"","message":""}}
You need to place the onload event handler before you send the request.
This is because the event handler is then attached to the request bwdire it is sent.
See Item 5
https://xhr.spec.whatwg.org/#the-send()-method
for more information on how send() works.

Submit a form and get a JSON response without jQuery

I have a simple HTML form like this:
<div class="border-little text-center grey">
<form action="https://www.THIS IS MY URL.php" method="get">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit">
</form>
</div>
The operation is as follows:
The player enters a number, and the server answers using a JSON format.
My issue:
When I press "submit" My webpage leaves and redirects to the server page display a JSON formatted answer.
What I want to do:
I want to stay on my page and be able to receive the answer in JSON format and display them below my form instead of being redirected to the server page.
More details:
example of JSON answer I get from the server:
{"guess": "lower"}
I cannot use any kind of JavaScript library so JQuery is forbidden.
you just use ajax method of js
function r_submit() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.THIS IS MY URL.php", true);
var params = {"player":document.getElementById("player").value};
xhttp.send(params);
xhttp.onload = function() {
alert(xhttp.responseText);
}
}
and execute r_submit() function button when you click button
here your html code will be like
<div class="border-little text-center grey">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit" onsubmit='r_submit()'>
</form>
</div>
i've written years ago a simple js part, that allows you to send XHR requests easily. it's a little deprecated but it is a simple template to understand how you CAN go on.
you could modernize it by using webworkers and make it closer to your setup. if you wish i could post an old prototype in JS from me with webworkers and so on (but some names of variables are in german..)
function getElement(inp)
{
return document.getElementById(inp);
}
function put(data,div)
{
getElement(div).innerHTML = data;
}
//information: autoput means: do you wish to write the raw response in a div? [0,1] - when 1 then put the id of the div in var div at the call of the function
function get(url,data,method,autoput,div)
{
var req;
if(window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = function()
{
if(req.readyState == 4 && req.status == 200)
{
if(autoput == 1)
{
put(req.responseText, div);
}
}
}
if(method.toLowerCase() == "get")
{
req.open("GET",url+data,true);
req.send();
}
else
{
if(method.toLowerCase() == "post")
{
if(data !== "")
{
req.open("POST", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(data);
}
}
}
}
It's possible to use iframe technique when jQuery is forbidden. Submit the form to the named iframe and wait for onload event. Modified html and js code will look like:
<div class="border-little text-center grey">
<form action="https://www.THIS IS MY URL.php" method="get" target="myframe">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit">
</form>
</div>
<iframe id="myframe" name="myframe"></iframe>
<script>
var myframe = document.getElementById("myframe");
myframe.onload = function() {
var iframeDocument = myframe.contentDocument || myframe.contentWindow.document; // get access to DOM inside the iframe
var content = iframeDocument.textContent || iframeDocument.body.textContent; // get text of iframe
var json = JSON.parse(content);
if (json && json.guess) {
// process the json here
alert(json.guess);
}
}
</script>

Getting error while submit form with ajax

When I was submitting post method form, given input fields values, not getting while submitting. If i using Ajax call in Jquery the form values serialize and submit it correctly, but in a javascript, Ajax call using FormData I'm getting error.
Can anyone resolve my problem.
Error:
Error: Can't set headers after they are sent. at
ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
apollo.model.save.unsetkey: Primary Key Field: name must have a value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="myForm" method="post" action="">
<div>
<label for="name">Enter name:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="surname">SurName:</label>
<input type="text" id="surname" name="surname">
</div>
<div>
<label for="age">Age:</label>
<input type="text" id="age" name="age">
</div>
<input type="submit" value="Submit!" onclick="loadForm()">
</form>
<p id="demo"></p>
<script>
function loadForm() {
var xhttp = new XMLHttpRequest();
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "http://127.0.0.1:8080/user", true);
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Content-Type', 'application/json');
var data = JSON.stringify(formData);
console.log('data = ', data);
xhttp.send(data);
}
</script>
</body>
</html>
You don't stop the default submission of the form, so when someone clicks the submit button the form will submit normally as well as through using Ajax. The solution is to bind a listener to the form submission and prevent the default behaviour.
Try this:
document.querySelector("#myForm").addEventListener("submit", function (event) {
event.preventDefault();
// ... Ajax call here ...
})

Redirect page after form submitting a form

<body onload="document.action.submit()">
<form name="action" method="post" action="https://en.educaplay.com/en/registrar.php" >
<input type="hidden" name="action" value='loginTicket'>
<input name="ticket" type="text" id="ticket" value="<%= session[:educa_key] %>">
<input type="submit" name="entrar" id="entrar2" value="Sign in" class="btn">
</form>
Now, I want to redirect the submitter to any page of my choice after the form data has been submitted, but the action resides on another website where I cannot edit. Is it possible to redirect the user to any page after he has submitted the data to that site? I have checked a number of suggestions but not sucess at this point. thanks in advance
If you do not have to wait for the answer, you can use javascript (jquery if you want and can) for this:
$("#entrar2").click(function(){
$(location).href(link);
});
In your registar.php file, add header('Location: https://www.example.com/example.html');
This isn't necessarily JavaScript, but it's probably the most efficient method.
When you submit a form, there will be an automatic browser redirection to the URL you specified in the action attribute of your form. Here is a minimal example:
<form action="http://stackoverflow.com">
<input type="text">
<input type="submit" value="Submit">
</form>
Now, if you want to code a form properly, you should follow the Post/Redirect/Get pattern. Ajax is a viable solution for what you want to do:
(function () {
// Dummy submit handler
function handler() {
var xhr = new XMLHttpRequest(),
url = "action.php",
params = "foo=Foo&bar=Bar";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
location.href = "http://stackoverflow.com";
}
}
xhr.send(params);
}
})();
You have to send your data to other website using curl before form submitted.Where you can process your data or store it . And after successful response from other page you can redirect user to any page
Your submission will cancel the redirect.
<form name="form1" id="form1" method="post" onsubmit="return redirect()">
<input type="submit" class="button4" name="order" id="order" value="Place Order" >
</form>
<script>
function redirect() {
window.location.replace("login.php");
return false;
}
</script>
OR
document.getElementById("formId").onsubmit=function() {
window.location.replace("https://jsfiddle.net/");
return false;
}

Redirecting users after they submit a form

I'm trying to make a basic form that redirects users to any given web page I choose after they submit their response. Although the action element is located on a site that I can not manipulate.
How would I go about doing this?
<form method="POST" action="https://docs.google.com/forms/d/1dAp52ALtiu8tEt8UY-Rs7WcKn36pI1vBItmGl0sV0Ik/formResponse">
<input type="text" name="entry.139518212" value="">
<input type="submit" name="submit" value="Submit">
</form>
Ajax may be helpful for you. you can submit your form through Ajax, get the response and do whatever you want.
you have to create an ajax function and call it on a click event
<input id="text" type="text" name="entry.139518212" value="">
<input type="submit" name="submit" value="Submit" onclick="sendData();">
and then create a js function:
function sendData(){
///getting text from input
text=document.getElementById('text').value;
var xmlhttp;
///browser compatibility
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
///if response was retrieved and no errors occured
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
///you can access the response
///put your redirection code here
}
}
xmlhttp.open("POST","https://docs.google.com/forms/d/1dAp52ALtiu8tEt8UY-Rs7WcKn36pI1vBItmGl0sV0Ik/formResponse",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("entry.139518212="+text);
}
Try this. You will need to have jQuery for it to work.
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('https://docs.google.com/forms/d/1dAp52ALtiu8tEt8UY-Rs7WcKn36pI1vBItmGl0sV0Ik/formResponse', function() {
window.location = 'http://www.whereveryouwanttogo.com';
});
return false;
});
});
</script>
From HTML Form Redirect

Categories

Resources