Fetch callback in React - javascript

I am trying to have a simple print run statement to ensure the callback is working correctly.
var CsvUpload = React.createClass({
uploadfile: function() {
console.log('trying')
var file = this.refs.file.files[0];
var formData = new FormData()
formData.append('files', file)
fetch('http://127.0.0.1:5000/add_csv_to_db', {
method :'POST',
body : formData
})
.then(() => {console.log('this worked')})
.catch((err) => {console.log(err)})
},
render: function() {
return (
<div>
<h4 className='sub-header'>CSV Upload</h4>
<form onSubmit = {this.uploadfile} encType="multipart/form-data">
<input type="file" name="file" ref="file"/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
})
On the server:
#app.route('/add_csv_to_db', methods=['GET','POST'])
def add_rows():
file = request.files['files']
x = io.StringIO(file.read().decode('UTF8'), newline=None)
csv_input = csv.reader(x)
for row in csv_input:
if row[0] == 'Email':
pass
else:
print(row)
tasks.add_User(row)
print('completed')
return json.dumps('success!')
I see "completed" print out in the server.
In the console I see "trying" but it doesn't print "This worked"
What am I doing wrong?

Have you tried adding submission event as your uploadFile function's parameter and then calling preventDefault() on it? Your app might be refreshing on submission, and that is why you never see "this worked" printed out.
This is what I mean:
var CsvUpload = React.createClass({
uploadfile: function(e) {
e.preventDefault();
console.log('trying')
...

Related

Pages refreshes on form submit even though I am using preventDefault

I am trying to stop the page from refreshing when submitting a form by using this:
window.addEventListener("load", function () {
let settings_form = document.getElementById("settings_form");
// handle form submit
settings_form.addEventListener("submit", function (e) {
e.preventDefault(); // before the code
save_settings();
// Should be triggered on form submit
console.log("hi");
return false;
});
});
But it does not work.
If I comment the save_settings method the page won't reload. Obviously, I need that method.
function save_settings() {
// let form = document.getElementById("settings_form");
let json_data = toJSONstring(settings_form);
console.log(json_data);
post_data("api/settings/change", json_data).then((send_response) => {
console.log(send_response);
conn_status = 1;
// logs to page
// get_settings() // update interface with newer settings
get_info();
});
}
I don't know which function makes e.preventDefault(); to not work.
For more context:
// parse form data into json
function toJSONstring(form) {
let object = {};
console.log(form);
let formData = new FormData(form);
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if (!Reflect.has(object, key)) {
object[key] = value;
return;
}
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
});
console.log(JSON.stringify(object));
return JSON.stringify(object);
}
// send/post json
async function post_data(api_path, json_data) {
let post_url = ROOT_URL + api_path;
const response = await fetch(post_url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: json_data,
});
//check
if (!response.ok) {
conn_status = 0;
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
return await response.json();
}
<form id="settings_form" class="settings_form">
<label for="wifi_ssid">Change SSID</label>
<input type="text" name="wifi_ssid" id="wifi_ssid" />
<label for="wifi_pass">Change Password</label>
<input type="text" name="wifi_pass" id="wifi_pass" />
<label for="ap_ip">Change IP Address</label>
<input type="text" name="ap_ip" list="ap_ip" />
<datalist id="ap_ip">
<option>192.168.100.20</option>
</datalist>
<input type="button" value="Save Settings" id="submit_btn">
</form>
I have also tried listening to the click event on the button:
window.addEventListener("load", function () {
let button = document.getElementById("submit_btn");
// handle form submit
button.addEventListener("click", function (e) {
e.preventDefault(); // before the code
save_settings();
// Should be triggered on form submit
console.log("hi");
return false;
});
});
Later Edit:
I am running a local mock-up JSON server in order to test my code.
I've tried the code here: https://jsbin.com/xogozovawe/1/edit?html,js,output and it works.
Might this be the local server's fault ?

How do I get and print a variable stored in localStorage with a POST request?

In an application in Flask, I need to take a user data from a form to store it with the "localStorage" function and print it on a new page after a POST request allowing to keep the printed name even if the page restarts. I have this code:
index.html:
<body>
<form id="registro" action="{{ url_for('chatroom') }}" method="post">
Ingresa al chat <br/>
<p><input type="text" id="usuario" name="usuario" placeholder="Usuario">
</p>
<input type="submit" id="guardar" value="Enviar" /><br>
</form>
</body>
Function in Python/Flask:
#app.route("/chatroom", methods=["POST"])
def chatroom():
Usuario = request.form.get("usuario")
return render_template("chatroom3A.html", Usuario=Usuario)
chatroom3A.html
<body>
…………………………..
<div>Bienvenid# <label type="text" id="bienvenido"></label></div>
…………………………….
</body>
Code in Javascript:
if (localStorage.getItem('userlog')) {
const TheUserlog = localStorage.getItem('userlog');
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#registro').onsubmit = () => {
// Initialize new request
const request = new XMLHttpRequest();
const nombre = document.querySelector('#usuario').value;
localStorage.setItem("userlog", nombre);
document.getElementById("usuario").value = "";
request.open('POST', '/chatroom');
const data = new FormData();
data.append('usuario', usuario);
// Send request
request.send(data);
// Callback function for when request completes
request.onload = () => {
const TheUserlog = localStorage.getItem('userlog');
if (request.status == 200) {
document.querySelector('#bienvenido').innerHTML = TheUserlog;
}
}
};
});
when chatroom3A.html is rendered, the page does not print the data ("usuario") from the form into index.html. I do not know how to indicate the contents to print with "innerHTML", perhaps with the function "responseText". I hope you can help me.

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();
} );
} );

How to prevent the browser from redirecting to a new page when submitting a form?

I use an AJAX call to a method that returns JSON. How can I read the returned JSON without being redirected to a new empty page?
[HttpPost]
public JsonResult Test()
{
return Json("JSON return test", JsonRequestBehavior.AllowGet);
}
#model List<POC.Web.Intranet.Models.AttachmentPropertyViewModel>
<div>
#using (Ajax.BeginForm("Test", "DMS", new AjaxOptions { HttpMethod = "POST", OnSuccess = "endMethod()", OnBegin = "beginMethod()" }))
{
<h6>Properties</h6>
for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(item => item[i].AttachmentPropertyId);
#Html.HiddenFor(item => item[i].AttachmentMetaDataId);
<label>#Model[i].AttachmentPropertyName</label>
#Html.TextBoxFor(item => item[i].AttachmentPropertyValue, htmlAttributes: new { #class = "form-control property-value-txtbox" });
<br />
}
<input type="submit" id="btnSaveChanges" value="Save Chnages" />
}
<hr />
</div>
<script>
function beginMethod() {
alert("Start");
}
function endMethod() {
alert("Finish");
// also here i want to read the incoming json
}
</script>
First of all , you do not need JsonRequestBehavior.AllowGet because you do a POST request.
[HttpPost]
public JsonResult Test()
{
return Json("JSON return test");
}
Then, change this:
OnSuccess = "endMethod()", OnBegin = "beginMethod()"
To
OnSuccess = "endMethod", OnBegin = "beginMethod"
And in your script, pass response parameter to get json result from controller.
function endMethod(response) {
console.log(response);
alert("Finish");
// also here i want to read the incoming json
}
You can stop the redirection and perform your Ajax calls by following one of the two methods given below.
Changing the button type to button from submit.
Or calling the JavaScript function on form submit by preventing the default action of submitting the form by utilizing the code snippet below,

using WinJS.xhr to post variables to a URL

Am trying to create a login page for my windows 8 app, am using Html5 and javascript.. so have tried to use winjs.xhr to post what is in the textboxes as variables to a specific url which is a php script so this is my example of the url "http://example.com/api/username=username&password=password" am using winjs.xhr to post these variables to the url but am not getting any response even in the console.log
this is my code
<script>
function handlelogin(){
document.getElementById("box").onsubmit = function(){
if(document.getElementById("email_address").value ==""){
document.getElementById("errormessage").innerHTML= "Please Provide Your Email Address";
return false;
}else{
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if(success == 1703){
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
};
}
window.onload = function () {
handlelogin();
}
</script>
<form id="box" method="post" name="loginform">
<p>Email address</p>
<div class="email_address"><input type="text" id="email_address" /></div>
<p>Password</p>
<div class="password"><input type="password" id="password" /></div>
<p><span id="errormessage"></span></p>
<div class="button"><input type="submit" id="login" value="Sign In"/></div>
<p>ForgotPassword?</p>
</form>
First - don't use a submit button. Use a input type="button". No submit required, you are simply reading the values on the page.
Second - attach the event handler for the button's click event. Doing this 'onload' for the window isn't the right place.
Third - don't use 'onsubmit' for your 'box' element. There is no form submission going on here. There shouldn't usually be a form submit in WinJS - that's for a browser posting the page to the server. You already are POSTing your data. See the updated code:
I highly recommend putting ALL javascript into separate files, as you'll get bytecode optimization that way. Inline Javascript isn't optimized for the next load. A common way you could do this is include the onload code below (where I assign onclick) in your js file like so
app.onactivated = function (args) {
..
..
..
args.setPromise(WinJS.UI.processAll().then(function () {
document.getElementById("login").onclick = handlelogin;
}));
..
..
}
};
But the answer directly for your question above is:
<script>
function handlelogin() {
if (document.getElementById("email_address").value == "") {
document.getElementById("errormessage").innerHTML = "Please Provide Your Email Address";
return false;
} else {
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({
type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if (success == 1703) {
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
}
window.onload = function() {
document.getElementById("login").onclick = handlelogin;
};
</script>
Check out some of the sessions in App Builder where they discuss JavaScript projects http://aka.ms/stackbuilder

Categories