How to prevent html form refresh on submit? - javascript

Hello after searching and trying a lot , i am not able to find the issue so that I am seeking your help to solve my issue.
Here I have a form while clicking on submit button it should call the javascript function and should not redirect or refresh the page .
Here I want to send mail using SMTPJS with attachments by filling the form and choosing the image once the form submitted it should call the sendEmail() function and mail should be send, but when i click on the submit button it's refreshing the page and it's not working accordingly.
<form onsubmit="sendEmail(); reset(); return false">
<div class="col-md-12">
<div class="form-floating">
<input type="file" class="form-control" id="fileupload" required>
<label for="phone">Upload file</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary w-100 py-3" type="submit" style="background-color: #0e2e50;">Upload</button>
</div>
</div>
</form>
<script>
function sendEmail() {
var file = event.srcElement.files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function () {
var dataUri = "data:" + file.type + ";base64," + btoa(reader.result);
Email.send({
Host: "smtp.elasticemail.com",
SecureToken :"************"
To: 'mail#mail.com',
From: "mail#mail.com",
Subject: "Form Enquiry",
Body : "Sending file:" + file.name,
Attachments : [
{
name : file.name,
data : dataUri
}]
}).then(
message => alert(message)
);
};
}
</script>
I think the issue is in this line 'var file = event.srcElement.files[0];' because from this line it's refreshing the page and a Question mark (?) is coming in the URL. ex.page.html?
One more thing if i am calling the sendEmail() function in the onchange event of the input type file then it's working fine, why so?

You have two problems.
Typo
The first is a typo and is highlighted by the browser telling you:
Uncaught SyntaxError: missing } after property list note: { opened at line 24, column 19
This exception is preventing the function from being created, so the onsubmit function errors when it calls it, and you never reach the return false that prevents the form submission.
Read the error messages in the console in the browser developer tools.
You are missing a comma between SecureToken :"************" and To: 'mail#mail.com'.
Forms don't have files
You said:
var file = event.srcElement.files[0];
Which gets the element that triggered the event (since it is a submit event, that is the <form>) and you try to read the files property from it.
The browser tells you this:
Uncaught TypeError: event.srcElement.files is undefined
Read the error messages in the console in the browser developer tools.
The files property can be found on <input type="file">, not on the <form>.
You need to find the correct element:
var file = event.srcElement.querySelector('[type="file"]').files[0];
Asides
To generally make life easier and avoid these sorts of issues:
Use a linter, like ESLint, and an editor that can use it as a plug in
Use a code formatter to indent code and help locate syntax errors
Don't use intrinsic event attributes (like onsubmit); do use addEventListener
Pay attention to what your debugging tools are telling you

Just change it a little bit:
<form onSubmit="sendEmail(event)">
...
</form>
function sendEmail(event) {
event.preventDefault();
...
}

Related

form button not recognising function

I have an HTML file with a basic form. I am calling a function on button click, but on click I receive "function is not defined". Everything appears to be in order vis-a-vis pointing to files, so I'm not sure where the disconnect is.
This is the layout:
and these are my index.html and main.js, respectively:
<!--index.html-->
<form action="" method="get" class="form">
<label for="form-input">Paste Key Here: </label>
<input type="text" name="Key Input" id="form-input">
<button id="form-button" type="button" onclick="GWAPIUser()">Click Here!</button>
<script type="application/javascript;charset=utf-8" src="/public/javascripts/main.js"></script>
</form>
/* main.js */
const key = 'authkey';
async function GWAPIUser() {
const response = await fetch(`https://api.guildwars2.com/v2/account/achievements?access_token=${key}`);
const data = await response.json();
console.log(data);
};
Directory was made with express-generator. This is my first time using it, so I'm not sure if that means anything.
Finally, this is the error I receive:
Uncaught ReferenceError: GWAPIUser is not defined at HTMLButtonElement.onclick (?Key+Input=:18)
Browsers do not like application/javascript;charset=utf-8 as a value for the type attribute.
"Non-modular JavaScript" is the default type for a script so you should omit the type attribute entirely in this case. Only include it if you need to specify type="module" or as a hack to store data in an element without rendering it.
<script src="/public/javascripts/main.js"></script>

Selenium Python - Upload image when element seems to be hidden

So basically I have problem uploading some photo using Selenium Python
input element seems to be hidden in the page so the .sendkeys method at still I run into some errors.
this is html code of the input element
<div data-react-class="ImageUploadForm" data-react-props="{}" data-react-cache-id="ImageUploadForm-0">
<input class="hidden" type="file" accept="image/jpeg, image/jpg, image/png, image/gif">
<button class="btn btn-lemonfrog text-lg" type="button">Upload photo</button>
</div>
base_path = Path(file).parent
filepath = (basepath / "../core/attachments/clientstackphoto.jpeg").resolve()
hiddenuploaderinput.sendkeys(filepath)
right now after running above code I'm getting type error :
value = (PosixPath('........./core/attachments/clientstackphoto.jpeg'),)
def keys_to_typing(value):
"""Processes the values that will be typed in the element."""
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = str(val)
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
E TypeError: object of type 'PosixPath' has no len()
../../venv/lib/python3.7/site-packages/selenium/webdriver/common/utils.py:150: TypeError
I expect to upload photo successfully, maybe some js injection will help ?
Based on your error message, I'm not entirely convinced the error message is caused by the hidden file input. If it were, I would expect an ElementNotVisibleException.
However, I do see that the input is hidden, so we should run some JS to reveal the input and perhaps we can rule that out as a potential issue.
Code to show image input
fileInput = driver.find_element_by_xpath("//input[#type='file']")
# display file input so we can send keys
driver.execute_script("arguments[0].style.display = 'block';", fileInput)
Alternatively, you may need to execute script on the class attribute instead:
driver.execute_script("arguments[0].setAttribute('class', 'visible')", fileInput)
Once you execute JS to make the file input visible, you can just send_keys to it like any other input:
fileInput.send_keys("PATH/TO/FILE/HERE")

My form submission get blocked because the frame is sandboxed and the 'allow-forms' permission is not set

I'm trying to build a custom form and submission post for Hubspot.
I have the following code
HTML
<head>
<script src="prezzi-form-submit.js"></script>
</head>
<body>
<form class='form-inline' id='my-custom-form'>
<div class="form-group">
<input type='email' class='form-control' placeholder='Your email address' required>
</div>
<button class="btn btn-primary" type='submit'>Sign up</button>
</form>
<!-- Actual form that gets submitted to HubSpot -->
<div class="hidden" id='hubspot-form'>
<script charset="utf-8" src="//js.hsforms.net/forms/current.js"></script>
<script>
hbspt.forms.create({
portalId: 'my-portal-id',
formId: '92b9b82a-0da2-4e23-8a30-04541c05ce6d',
onFormReady: function($form) {
$form.attr('target', 'hubspot-iframe');
}
});
</script>
<!-- iFrame that data will get submitted to. This hack stops the page redirect. -->
<iframe name="hubspot-iframe" id="hubspot-iframe" sandbox="allow-forms"></iframe>
</div>
</body>
JS (prezzi-form-submit.js)
// // Send form data to HubSpot from the client.
function submitToHubSpot(data) {
var $form = $('#hubspot-form form'),
k;
// Loop through each value and find a matching input.
// NOTE: Doesn't support checkbox/radio.
for (k in data) {
$form.find("input[name='" + k + "']").val(data[k]);
}
$("form input:submit").trigger("click");
}
// Here's how you'd use this.
$('#my-custom-form').on('submit', function() {
var formData = {};
$(this).serializeArray().forEach(function(data) {
formData[data.name] = data.value;
});
submitToHubSpot(formData);
// We sent the data. Now do whatever else you want.
alert('Gee, thanks Jonathan! Now I can focus on onboarding my customers with Appcues!');
window.location.href = 'http://appcues.com';
})
When I press the submit button, I get the following error in the console
Blocked form submission to " " because the form's frame is sandboxed
and the 'allow-forms' permission is not set.
As you can see I have the
sandbox="allow-forms"
set in the I frame but it isn't working.
How can I fix this error?
Sometimes when you click a link from an application, the tab opened will have javascript disabled/sandboxed.
Close the tab and reopen the same URL in a fresh tab, it might work.
Ran into the same problem with an iFrame form on Hubspot and got the same JS error. Discovered it has to do with the live preview using the HS Design tool.
In the drop down at the top there's the "Live preview with display options" then the "Preview without display options". It's the "preview with display options" selection that makes it "Sandboxed", try the one without. Hope this is helpful for someone.
Instead of setting the allow-form attribute in the html, set it within the .js using
el.setAttribute('sandbox', 'allow-forms');
It is because the frame itself is being sandboxed but the script is being called prior to the form being submitted which triggers submission of the frame but since the user wouldn't be able to submit, it wont call the iframe properties to respect the attribute set there

React.js 'Unexpected token' < when using form tag

I've been making a web app using mern stack with babel, webpack, redux and semantic-ui-react.
But I got an error saying
"Unexpected token <" in bundle.js.
This error only occurs when I send a request clicking a button in form tag. If I make the page without a form tag, it works fine without any error.
This is my codes in React.
handleUpload(title, contents, userId) {
return this.props.createPostRequest(title, contents, userId).then(
() => {
if(this.props.post.status === 'SUCCESS') {
alert('Your post is saved successfully.');
browserHistory.push('/');
return true;
} else {
alert('Save Fail: ' + this.props.post.failReason);
return false;
}
}
);
}
render() {
return(
<div className="Write">
<br/>
<br/>
<Form>
<Container text>
<Form.Input label='Title' fluid name='title' placeholder='title'
value={this.state.title} onChange={this.handleChange}>
<input/>
</Form.Input>
<Form.TextArea rows='20' name='contents' placeholder='Write here!'
value={this.state.contents} onChange={this.handleChange}>
<textarea/>
</Form.TextArea>
<br/>
<Button.Group>
<Button color='orange' as={Link} to='/'>Cancel</Button>
<Button.Or/>
<Button positive onClick={this.handleUpload}>Save</Button>
</Button.Group>
</Container>
</Form>
</div>
);
}
When I type letters and click the save button, I can see an alert message saying
Your post is saved successfully..
And also the data I put is saved in mongodb. But after I click ok, the url changes from 'localhost:3000/post/write' to 'localhost:3000/post/write?title=blah&contents=blah'. blah in the url is what I put in input tags. Then console says
Unxpected token <.
But, if I don't use a form tag in above codes, it works fine, which I totally have no idea what's wrong about.. The Form tag is from semantic-ui-react. So I need it. If I don't use Form, it would work fine but I should give up the design provided from semantic-ui.
Is there anyone who knows about this? I guess it's related to the HTTP POST in form tags that make trouble for react.js to understand bundle.js in index.html after the server-side handles the post request from that form tag.
TL;DR
handleSubmit = (e) => e.preventDefault()
<Form onSubmit={this.handleSubmit} />
Why?
By default, an HTML form will make GET request to the current URI on submit, see here. Also by default, a button in a form will submit it:
http://codepen.io/levithomason/pen/RpEwWP
<form onsubmit="alert('submitted!')">
<button>I'll submit</button>
<button>Me too</button>
</form>
What is happening is, React is rendering a <form /> with some <button />s inside of it and when you click them, it is making a GET request to the current URI with the form data.
Going out on a limb, I bet your local server that is serving your app doesn't have a handler to accept this request. Going further, I bet it also has a fallback that responds with the index.html on unknown requests. This is commonplace for single page apps to allow the app's soft router to handle routing, rather than the server. This is probably causing your request for bundle.js to actually receive the index.html, hence the unexpected token.
Since you've stated:
...if I don't use a form tag in above codes, it works fine...
Simply preventing the form submit should solve it for you.

Submitting an image to Facebook with Javascript and HTML form

I’m going crazy with image upload to Facebook. I’ve tried HTML5 drag and drop methods, Dropzone.js, as well as uploading to my own server before submitting the image via PHP. But the only one I can make work (because of my inexperience, I’ll admit) and that doesn't involve uploading the image to my own server, is by using a HTML form as shown in the Facebook documentation:
<form id=“upload_form” enctype="multipart/form-data" action=“https://graph.facebook.com/event_id/photos?access_token=an_access_token” method="POST">
Please choose a photo
<input name="source" type="file"><br/><br/>
Say something about this photo:
<input name="message" type="text" value=""><br/><br/>
<input type="submit" value="Upload"/><br/>
</form>
I dynamically generate it in Javascript and use var’s to fill in event_id and access_token.
This works fine, so all my permissions and authorising are correct. Now what I’d like to do is handle the response because the browser does as you’d expect when the user clicks submit and displays basic text showing the post id and whatnot.
So, I created a button and bound the following to it’s click event:
var fd = document.getElementById('upload_form');
if (fd) {
console.log('Sending');
var XHR = new XMLHttpRequest();
XHR.addEventListener('load', function(data) {
console.log('XHR finished:');
console.log(data);
});
XHR.addEventListener('error', function(data) {
console.log('XHR ERROR:');
console.log(data);
});
var graph_url = 'https://graph.facebook.com/'+event_id+'/photos?access_token=' + access_token;
XHR.open('POST', graph_url);
XHR.send(fd);
}
Once the user has selected an image and clicks my button to execute the above XHR completes the send and reports as finished, but Facebook replies with:
(#324)Requires upload file.
Please can someone show me where I’ve gone wrong - it’s been a problem for days now!
If you willing to use jquery and jquery.ajaxForm plugin
<!-- You form code stay Make sure your form.action url is valid ajaxForm use that as url -->
<form id=“upload_form” enctype="multipart/form-data" action=“https://graph.facebook.com/event_id/photos?access_token=an_access_token” method="POST">
Please choose a photo
<input name="source" type="file"><br/><br/>
Say something about this photo:
<input name="message" type="text" value=""><br/><br/>
<input type="submit" value="Upload"/><br/>
</form>
//your javascript to upload the image togather with message
// put this in a button, not submit button
$('#upload_form').ajaxForm({
complete: function(data) {
//process fb response
}
});
I suggest you use Fiddler to catch both connections, with and without XMLHttpRequest and see which is the actual difference between both request, I don't actually know what XHR.send(fd); does, but maybe it's sending the form content itself, not submitting it?
Fiddler is a very useful tool when connecting to external APIs

Categories