How to get html form without form id [duplicate] - javascript

This question already has answers here:
How to access HTML element without ID?
(7 answers)
Closed 2 years ago.
i'm creating a system than get html form values and send it to API. I created a simple html form with javascript to get values to send, but i get form using form ID, is there any way to get form without id ? i'll creating this to work in website than have only one .
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="teste1.js"></script>
</head>
<body>
<form id="myForm">
<label for="myName">Send me your name:</label>
<input id="myName" name="name" value="John"><br>
<label for="myEmail">Send me your email:</label>
<input id="myEmail" name="email" value="Exemplo#exemplo.com"><br>
<input type="submit" value="Send Me!">
</form>
</body>
</html>
teste1.js
window.addEventListener( "load", function () {
function sendData() {
const XHR = new XMLHttpRequest();
const FD = new FormData( form );
const data = {
name: FD.get('name'),
email: FD.get('email')
}
// Define what happens on successful data submission
XHR.addEventListener( "load", function(event) {
alert("Success.");
} );
// Define what happens in case of error
XHR.addEventListener( "error", function( event ) {
//alert( 'Oops! Something went wrong.' );
} );
// Set up our request
XHR.open( "POST", "API_URL" );
XHR.setRequestHeader('Content-type', 'application/json')
// The data sent is what the user provided in the form
XHR.send(JSON.stringify(data));
}
// Access the form element...
const form = document.getElementById( "myForm" );
// ...and take over its submit event.
form.addEventListener( "submit", function ( event ) {
event.preventDefault();
sendData();
} );
} );
look i get form with
const form = document.getElementById( "myForm" );
and
const FD = new FormData( form );
how get form without id, if it was like
<form>
...

You may try document.forms[0]
And if you have name assigned to form then it can be through, let say it something like
<form name="myform"></form>
document.forms.myform

Related

Post data info to CGI script using javascript

I have this very simple HTML Form. I want to pass the input to a CGI script (Python), which will store them into mysql table.
<!DOCTYPE html>
<html>
<body>
<h2>Cadastro</h2>
<form name="cadastro" id="cadastro" action="/cgi-bin/cadastro.py" method="POST">
<label for="nome">Nome completo:</label><br>
<input type="text" id="nome" name="nome" required><br>
<label for="mae">Nome completo da mãe:</label><br>
<input type="text" id="mae" name="mae" required><br>
<br><br>
<input type="submit">
</form>
</body>
</html>
The form works great and data is correctly stored into the mysql table.
However, I wanted to make a "successful" message when clicking the submit button, instead of redirecting it to the cgi script.
I believe the easiest way to do that is using javascript. Then, I tried adding this to the code:
<script>
const cadastro = document.getElementById("cadastro");
cadastro.addEventListener("submit", (e) => {
e.preventDefault();
const request = new XMLHttpRequest();
request.open("post", "/cgi-bin/cadastro.py")
request.send();
});
</script>
Here is the python script, in case its necessary:
print("Content-type: text/html\r\n\r\n")
import cgi, mysql.connector
db = mysql.connector.connect(
host = "xxx",
user = "yyy",
password = "aaa",
database = "bbb",
)
cadastro = cgi.FieldStorage()
def add_cliente(nome, mae):
cursor = db.cursor()
cursor.execute("INSERT INTO cadastro (nome, mae) VALUE (%s, %s)", (nome, mae))
db.commit()
return print(cursor.rowcount, "record inserted.")
add_cliente(cadastro.getvalue("nome"), cadastro.getvalue("mae"))
However, the user input is stored as NULL in the mysql table. Could someone help, please?
It comes down to the script not sending any data, thus the NULL values. As mentioned, the cgi script was working good.
Here is an example javascript code, extracted from here:
window.addEventListener( "load", function () {
function sendData() {
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
const FD = new FormData( form );
// Define what happens on successful data submission
XHR.addEventListener( "load", function(event) {
alert( event.target.responseText );
} );
// Define what happens in case of error
XHR.addEventListener( "error", function( event ) {
alert( 'Oops! Something went wrong.' );
} );
// Set up our request
XHR.open( "POST", "https://example.com/cors.php" );
// The data sent is what the user provided in the form
XHR.send( FD );
}
// Access the form element...
const form = document.getElementById( "myForm" );
// ...and take over its submit event.
form.addEventListener( "submit", function ( event ) {
event.preventDefault();
sendData();
} );
} );

Trying to get an image url from AJAX, getting status = 0

I have an input, say "xxx".
the server returns an image in GET method in: https://website.com/xxx
All I want is for the image that returns when going to that url to be displayed.
Wrote a little script for it but i always get status = 0. I wonder why it is and how can it be 200.
<!-- templates/homeDEV.html -->
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<form method="GET">
<p>AJAX Address: <input id="address" type="text" name="address" maxlength="64" size="64"></p>
<p><input type="submit" value="Generate AJAX" onclick="loadImage()"/></p>
</form>
<script>
function showImage(src) {
var img = document.createElement("img");
img.src = src;
document.body.appendChild(img);
}
function loadImage() {
var theReturn = document.getElementById('address').value;
var url = "https://monkey-g.herokuapp.com/monkey/" + theReturn;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
showImage(url);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
</body>
</html>
You are running your JavaScript when you click the submit button in a form.
This:
Initiates the Ajax request
Submits the form
Leaves the page
Cancels the Ajax request (because there is no longer any JS to handle the response)
Loads the new page
Remove the form, and make the button a JS (type="button") button.
You don't need to AJAX an image. There's not possible way to stuff an Image from an AJAX request into an image tag. The image tag itself is all you need.
Also, as Quentin said, your page is going to refresh before your ajax call is made anyway if you use a form.
function loadImage() {
var theReturn = document.getElementById('address').value;
var url = "http://monkey-g.herokuapp.com/monkey/" + theReturn;
var img = new Image();
img.src = url;
document.body.appendChild(img);
}
<p>AJAX Address: <input id="address" type="text" name="address" maxlength="64" size="64">
<p><input type="button" value="Generate AJAX" onclick="loadImage()" /></p>

Javascript fetching text from textarea & posting to php page

I've got a textarea on a page used to submit posts, like in a chat or forum. To show how the posts are formatted I'm trying to get a preview function to work, using javascript. Once the preview-link is clicked, the script should fetch the text from the textarea (id = inputinsertcommentary) and post it to a popup window (postvorschau.php), where it's previewed using the $_POST variable.
Here's my script:
function postvorschau() {
var url = 'www.page.com/folder/postvorschau.php';
var form = document.createElement('form');
form.action = url;
form.method = 'POST';
form.setAttribute("target", "_blank");
var text = document.getElementById('inputinsertcommentary').value;
var postname ='posting';
var input = document.createElement('input');
input.type = 'hidden';
input.name = postname;
input.value = text;
form.appendChild(input);
form.submit();
}
And here's the link where the function is called:
<a href='javascript: postvorschau();'>Postvorschau</a>
As far as I can see from my browser log (firefox), the function is called and doesn't produce any errors. However, there's no popup window opened - I suppose something in my syntax is wrong, but from looking at similar examples I can't really figure out what. Any help is greatly appreciated!
A basic example of using ajax to send the contents from the textarea to the backend script. The php script presumably formats the data and then prints it out.
<?php
/* postvorschau.php: format data and send back to callback */
if( !empty( $_POST ) ) {
/* you would send back formatted data probably - whatever that might be */
exit( json_encode( $_POST, true ) );
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>html preview</title>
</head>
<body>
<form>
<textarea name='inputinsertcommentary' cols=80 rows=10 style='resize:none' placeholder='Enter comments / data here and use preview button / link'></textarea>
<a href='#'>Preview</a>
</form>
<script>
var olnk=document.querySelectorAll('form a')[0];
olnk.onclick=preview;
function preview(e){
/* get textarea ~ you could use ids instead of course */
var oTxt=e.target.parentNode.querySelectorAll('textarea')[0];
/* create request object */
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
/* invoke callback with response data */
if( xhr.readyState==4 && xhr.status==200 ) cbpreview.call( this, xhr.response );
};
xhr.open( 'POST', '/folder/postvorschau.php' );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( 'data='+oTxt.value );
}
function cbpreview(r){
alert( r );/* use this callback to generate the "popup" using "r" as the data, either formatted or raw */
}
</script>
</body>
</html>

Unable to receive something in PHP from XMLHttpRequest's "POST"

First off, here's my code:
HTML ("formdata-index-test.html"):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test page</title>
</head>
<body>
<form id="the-form" method="post" action="formdata-validation-test.php">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
<script src="formdata-fields-control-test.js" type="text/javascript"></script>
</body>
</html>
JS ("formdata-fields-control-test.js"):
var form = document.getElementById("the-form");
form.onsubmit = function() {
var q = document.getElementById("the-text").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("q="+q);
}
PHP ("formdata-validation-test.php"):
<?php
$example = $_POST['q'];
echo $example;
if (empty($example)) {
echo "Empty";
}
?>
Now, at the beginning, I wasn't getting anything as response, but after a few tries and changes in my code, I'm being able to receive that alert in the JS file. The weird thing is that, even receiving the alert, I'm still getting the "Empty" echo when the PHP page is loaded after the form submission. Does anyone know why is it happening? My final goal is just to send the text from the HTML file to the PHP file, and then to database (that is, the "responseText" is not really necessary, and it's here just with test purposes), but apparently, PHP is not really receiving what JS sends, while JS receives what PHP sends. Does it make any sense?
The submit button is clicked and a submit event fires on the form.
The JavaScript is running. It is making an HTTP request to the PHP script with the data in it. Since you have forced it to be a synchronous request (don't do that, it locks up the event loop), the browser waits for the response before continuing. The JS is then processing the response, and alerting the value.
Then the form is submitted. It doesn't have a control with name="q", so for the second request to the PHP script, empty($example) will always be true.
If you want to stop the form being submitted then call preventDefault on the event object.
form.onsubmit = function(event) {
event.preventDefault();
try this :
1) in formdata-fields-control-test.js , make your script as a function :
function testFunction() {
var q = document.getElementById("the-text").value;
var params = "q="+q;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
};
2) in formdata-index-test.html , set action to empty and call the javascript function onsubmit :
<form id="the-form" onsubmit="return testFunction()" method="post" action="">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
the issue i think was with the form having an action and a onsubmit function together.

Ajax acting as GET method even though is POST method

Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"

Categories