Post data info to CGI script using javascript - 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();
} );
} );

Related

$_FILES not receiving input after AJAX with vanilla Javascript

I have a form that passes various types of input to an ajax call, which opens a php script. The script will do various things including processing the file, before echoing an array of variables.
All inputs go through $_POST regularly, and the file data is passed, too, but the file itself is not accessible from $_FILES.
I am not using jQuery, so most posts are hard to translate to my case.
I have seen a similar issue here,https://stackoverflow.com/questions/56878395/files-empty-after-ajax-upload but that solution doesn't seem to apply.
Here are the key excerpts from the code, thank you in advance for any tips!
var ajaxResponse = "";
var qForm = document.getElementById('myForm');
qForm.addEventListener("submit", function(e) {
e.preventDefault();
var formData = new FormData(qForm);
checkForm(formData);
console.log(ajaxResponse); //this shows the $_FILES var_dump
});
function checkForm(formData) {
var vars = "startDate=" + formData.get('startDate') +
"&qInvited=" + formData.get('qInvited');
ajaxRequestReturn("checkForm.php", vars);
}
function ajaxRequestReturn(phpRequest, vars) {
var req = new XMLHttpRequest();
req.open("POST", phpRequest, false); //not asynchronous, because I pass results to a global variable
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //removing the setRequestHeader doesn't seem to make any difference.
req.onload = function() {
ajaxResponse = this.responseText;
}
req.onerror = function() {
throw new Error("Bad request.");
}
req.send(vars);
// form.submit();
}
<form class="loginForm" id="myForm" method="post" enctype="multipart/form-data" action="thisPage.php">
<div>
<input type="date" id="startDateInput" name="startDate">
</div>
<div>
<input type="file" name="qInvited" required>
</div>
<input type="submit" id="submitBtn">
</form>
and the checkForm.php file is currently simply:
<?php
echo var_dump($_FILES);
?>
the var_dump($_FILES) should show the qInvited file in it, but it prints
array(0) {
}
instead.
To upload a file via ajax you have to pass a FormData object in your call to XMLHttpRequest.send.
Get rid of the checkForm function and call ajaxRequestReturn with formData as the second parameter.
Also, application/x-www-form-urlencoded is not the correct content type(its multipart/form-data), remove that line. The correct content type will be set automatically when you use the FormData object.

How can you read POST data from a javascript XMLHttpRequest in Golang?

Here's the javascript function called:
function cwk_submit_form() {
var form = document.getElementById("FORM_ID")
var XHR = new XMLHttpRequest();
const FD = new FormData( form );
for (const element of FD.entries()) {
console.log(element)
}
XHR.open( "POST", "http://localhost:8080/post_data" );
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHR.send( FD );
}
I left the console.log in there to mention that this does print out the correct data, meaning that the issue is seems to be in how the data is transferred.
The Golang code that receives the response is:
func post_data(w http.ResponseWriter, r *http.Request) {
log.Println("post was called")
r.ParseForm()
for key, value := range r.Form {
log.Printf("%s = %s\n", key, value)
}
}
Nothing is printed by this for loop.
If I use an HTML Form to submit like so:
<form action="//localhost:8080/post_data" method="POST">
<input type="text" name="field1" value="" maxLength="20"/>
<input type="text" name="field2" value="" maxLength="20"/>
<input type="submit" value="Sign in"/>
</form>
then the Golang code above works fine, which leads me to believe that the XMLHttpRequest format is the issue.
Your guess is right there is a problem in your js code.
For all requests, ParseForm parses the raw query from the URL and updates r.Form.
And hence, it will work when the Content-Type you send and the actual content type matches to application/x-www-form-urlencoded which happens in your HTML form case.
On the other hand, when you use FormData, it will be sent as multipart/form-data.
You need to replace your XHR.send(FD) with XHR.send(new URLSearchParams(FD)) in order to send the data in application/x-www-form-urlencoded.

How to get html form without form id [duplicate]

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

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>

XMLHttpRequest to Post HTML Form

Current Setup
I have an HTML form like so.
<form id="demo-form" action="post-handler.php" method="POST">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
I may have many of these forms on a page.
My Question
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
function getHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
So for example, say the javascript method demoRequest() was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest?
EDIT
Trying to implement a solution from an answer below I have modified my form like so.
<form id="demo-form">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button>
</form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
Button Event Listener
document.getElementById('updateBtn').addEventListener('click', function (evt) {
evt.preventDefault();
// Do something
updateProperties();
return false;
});
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().
Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);
request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest's method send():
var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert(xhr.responseText); }
xhr.open(oFormElement.method, oFormElement.getAttribute("action"));
xhr.send(new FormData(oFormElement));
return false;
}
</script>
</head>
<body>
<form method="POST"
action="post-handler.php"
onsubmit="return submitForm(this);" >
<input type="text" value="previousValue" name="name"/>
<input type="submit" value="Update"/>
</form>
</body>
</html>
This snippet is basic and cannot use GET. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction.
By the way I have used the following code to submit form in ajax request.
$('form[id=demo-form]').submit(function (event) {
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// fire off the request to specific url
var request = $.ajax({
url : "URL TO POST FORM",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
});
// prevent default posting of form
event.preventDefault();
});
With pure Javascript, you just want something like:
var val = document.getElementById("inputFieldID").value;
You want to compose a data object that has key-value pairs, kind of like
name=John&lastName=Smith&age=3
Then send it with request.send("name=John&lastName=Smith&age=3");
I have had this problem too, I think.
I have a input element with a button. The onclick method of the button uses XMLHTTPRequest to POST a request to the server, all coded in the JavaScript.
When I wrapped the input and the button in a form the form's action property was used. The button was not type=submit which form my reading of HTML standard (https://html.spec.whatwg.org/#attributes-for-form-submission) it should be.
But I solved it by overriding the form.onsubmit method like so:
form.onsubmit = function(E){return false;}
I was using FireFox developer edition and chromium 38.0.2125.111 Ubuntu 14.04 (290379) (64-bit).
function postt(){
var http = new XMLHttpRequest();
var y = document.getElementById("user").value;
var z = document.getElementById("pass").value;
var postdata= "username=y&password=z"; //Probably need the escape method for values here, like you did
http.open("POST", "chat.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", postdata.length);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postdata);
}
how can I post the values of y and z here from the form

Categories