Why is JS submitting form to the wrong URI endpoint? - javascript

I am trying to submit a form in JS, however I believe the endpoint URI specified in the action attribute does not consider the relative path of the HTML document.I think this may be due to the fact that the JS script and HMTL document are not located in the same directory. The HTML doc is index.html:
<!DOCTYPE html>
<html>
<body>
<div>
student name:
<input type="text" class="studentName"></input>
<button type="button" id="addStudentButton">Add</button>
</div>
<script src="/cdn/scripts/class/index.js"></script>
</body>
</html>
The imported JS script index.js is:
const addButton = document.getElementById('addStudentButton')
addButton.addEventListener('click', function () {
const studentName = document.getElementsByClassName('studentName')[0]
const form = document.createElement('form')
const element1 = document.createElement('input')
form.method = 'POST'
form.action = '/api/create'
element1.name = 'student'
element1.value = studentName.value
form.appendChild(element1)
document.body.appendChild(form)
form.submit()
})
When the form is submitted I get the following error response in chrome:
Cannot POST /api/create
This is because it should instead POST to /class/api/create, so I figured I should change the form attribute action accordingly to:
form.action = '/class/api/create'
however I then get the error response:
Cannot POST /class/class/api/create
Does anyone have any idea what the issue is?

Related

How to get source code of Input url inside div?

Here is my HTML and I want to show source code of url with (view-source+url) inside class .source-html from input when I click on button?
const input = document.querySelector("#input");
const button = document.querySelector(".view");
button.addEventListener("click", (x) => {
const url = input.value;
const sourceUrl = "view-source:" + url;
//Some code that show source of url inside div
});
<input id="input" type="text" />
<button type="button" class="view">View Source</button>
<div class="source-html"></div>
If possible, help me.
The modern browsers not allowed to load local source of the website. This is due to security policies. If you load other websites source into your site, then there is a chance to load malicious scripts.
Still if you try to load the view-source then you may encounter with "CORS error" or "Not allowed to load local resource: view-source:"
You can still use the below code to view the source of same origin sites.
const input = document.querySelector("#input");
const button = document.querySelector(".view");
button.addEventListener("click", (x) => {
const url = input.value;
//view source of same origin
$.ajax({
url: url,
success: function(x){
console.log(x);
}
})
});

How to have Javascript function save two text inputs into one text (.txt) file?

So I'm writing a webpage where the user inputs values into two textarea fields, and once they click on the submit button, the program is supposed to initiate a download of both text inputs and save them into a text file. So far, I've figured out how to have only one of the text inputs be saved to the text file, and I've been trying to figure out how to get my Javascript function to have this done for both text inputs. Here is my html and javascript code:
function saveIndex() {
var myBlob = new Blob([document.getElementById('textbox').value], {
type: "text/plain"
});
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "textfile.txt";
anchor.click();
window.URL.revokeObjectURL(url);
document.removeChild(anchor);
}
<body>
<label for="textbox">Textbox1</label>
<textarea id="textbox1"></textarea>
<label for="bio">Textbox2</label>
<textarea id="textbox2"></textarea>
<button type="button" id="bt" value="Exporter" onclick="saveIndex()" for="textbox"> EXPORT </button>
</body>
I know I need to probably create a new Blob for my second textarea tag, but I've tried that and also tried different ways to implement it into my function without any success. I cannot make another function for the second textarea tag, this must all be done within the current saveIndex() function. Any help would be greatly appreciated!
You were trying to get the value of an element with an ID of 'textbox' but there wasn't such an element. You have 'textbox1' and 'textbox2'. This code will retrieve both and concatenate them with a newline into your blob.
I've fixed up some errors in your HTML (the labels not linking correctly with their inputs), also please use let & const instead of ancient var!
function saveIndex() {
const boxString1 = document.getElementById('textbox1').value
const boxString2 = document.getElementById('textbox2').value
const myBlob = new Blob([`${boxString1}\n${boxString2}`], {
type: "text/plain"
});
const url = window.URL.createObjectURL(myBlob);
const anchor = document.createElement("a");
document.body.appendChild(anchor);
anchor.href = url;
anchor.download = "textfile.txt";
anchor.click();
window.URL.revokeObjectURL(url);
anchor.remove();
}
<body>
<label for="textbox1">Textbox1</label>
<textarea id="textbox1"></textarea>
<label for="textbox2">Textbox2</label>
<textarea id="textbox2"></textarea>
<button type="button" id="bt" onclick="saveIndex()">EXPORT</button>
</body>

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.
What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).
HTML:
<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script>
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>
</head>
<body>
<form >
player one name: <input type="text" id="firstname"><br>
player two name: <input type="text" id="secondname"><br>
<input type="submit" onclick="checkNames();"/>
</form>
</body>
</html>
JavaScript:
function checkNames(){
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
//window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
//window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}
I have commented the two other options I tried which also do not work.
You are using an HTML form... this means that your submit button will fire and try to submit your form.
In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.
function checkNames() {
event.preventDefault();
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
window.location.href = 'SOME-PATH/Game.html';
}
To redirect to a page in your computer you can use:
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';
There are more than one way of passing the values to another page. Here is an example using query string.
In the page that has the values.
var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;
In the page receiving the values.
var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];
Use
window.location="url";

Element within iframe's div not accessible in the current code

I have 2 HTML files namely a.html and b.html, One js file namely do.js.
Here are each the contents of each file:
a.html:
<head>
<script src="do.js" type="text/javascript"></script>
</head>
<body>
<button onClick = "doWork();">click me</button>
<iframe src = "b.html" id = "previewFrame"></iframe>
</body>
b.html (relevant part):
<div id = "container"></div>
do.js:
function doWork(){
var div = $('#previewFrame').contents().find('#container');
div.html("<input type = 'text' id = 'testElem' value = '12'><script>alert(document.getElementById('testElem').value);</script>");
}
When I run the above code, the content of the iframe gets replaced by the text box, however the alert fails.
I get a "type error" stating that document.getElementById... is null.
Can anyone please tell me what am I missing in the above code?
You are calling the Javascript function using document, but this object is from the parent document, not the document of the iframe, try with:
function doWork(){
var a = $('#previewFrame').contents().find('body');
a.html("<input type = 'text' id = 'testElem' value = '12'><sc"+"ript>alert($('#previewFrame').contents()[0].getElementById('testElem').value);</scr"+"ipt>");
}
See demo here.

Hidden form file POST in javascript

Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.

Categories

Resources