So i want to make a pure html and javascript form and submit it to server.
Here is my html form code:
<form id="email-signup" action="http://www.server.com" method="post">
<input id="firstname-input" type="hidden" name="firstname" value="">
<input type="text" name="email" placeholder="Input Email">
<input type="hidden" name="campaign[id]" value="1">
<input type="hidden" name="campaign[name]" value="Text Campaign">
<input type="submit" value="Submit">
</form>
And here is my javascript code:
var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
event.preventDefault()
fetch("http://www.endpoint.api", {
method: "POST",
body: new FormData(document.getElementById('email-signup'))
})
})
.then(() => {
alert('Selamat email anda sudah terdaftar!')
})
The problem is, whenever i submit an email to that form it redirects me to a new page with a response of success. I want to prevent that to happen and instead it will pop up an alert that tells me the email submission is succeeded.
You're putting the .then in the wrong place - put it right after the fetch, not after the event listener.
var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
event.preventDefault()
fetch("", {
method: "POST",
body: new FormData(document.getElementById('email-signup'))
}).then((res) => {
if (res.ok) alert('Selamat email anda sudah terdaftar!')
})
})
Consistent indentation will help you avoid problems like this in the future. (see your question, I fixed the formatting - should be pretty clear what the problem was now)
Possibly, you are putting JavaScript code before HTML and .then() after EventListner.
The solution will be to place JavaScript code after HTML and place .then() just after fetch.
<form id="email-signup" action="http://www.server.com" method="post">
<input id="firstname-input" type="hidden" name="firstname" value="">
<input type="text" name="email" placeholder="Input Email">
<input type="hidden" name="campaign[id]" value="1">
<input type="hidden" name="campaign[name]" value="Text Campaign">
<input type="submit" value="Submit">
</form>
<script>
var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
event.preventDefault()
fetch("", {
method: "POST",
body: new FormData(document.getElementById('email-signup'))
}).then(() => {
alert('Selamat email anda sudah terdaftar!')
})
})
</script>
Related
I am using Streamlit to build a simple app. In this app I made a simple form using FormSubmit to let people contact me. But I don't want them to leave the website when they click on Send button, so I am trying to send the form using AJAX.
To integrate JS in Python I am using Js2Py, but I can't solve this.
This is the form:
contact_form = """
<form id="myForm">
<input type="hidden" name="_captcha" value="false">
<input type="text" name="name" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your name" required>
<input type="email" name="email" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your email" required>
<textarea name="message" style="font-family:'Alegreya, serif';
font-size:20px;" placeholder="Your message here" required></textarea>
<input type="hidden" name="_template" value="table">
<button type="submit" value="Submit" id="sendButton" class="block">Send</button>
</form>
"""
so I made a javascript variable, to check when Send button is clicked:
check_submit = '''<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#sendButton").click(function(e) {
e.preventDefault();
var form = $('myForm'[0]);
var data = new FormData(form);
$.ajax({
method: "POST",
url: "https://formsubmit.co/my-email",
dataType: 'json',
data: data,
success: (data) => console.log(data),
error: (err) => console.log(err)
});
});
});
</script>
'''
then:
st.markdown(contact_form, unsafe_allow_html=True)
So I am passing the javascript variable into the function eval_js() from Js2Py:
js2py.eval_js(check_submit)
I got my form up, and an error message below the form:
JsException: SyntaxError: Line 1: Unexpected token <
and when I fill the form and clicking the Send button, nothing happens.
This means according to me that I misunderstood how to use JS2Py in Python!!!
Any help/suggestion to show me where I did wrong, is very appreciated
I am new with javascript, need help to post data to web service.
I have simple page:
<form action="#" class="simple-form">
<input id="A" type="text" autocomplete="off">
<input id="B" type="text" autocomplete="off">
<input id="amount" type="text" autocomplete="off">
</form>
<button align="middle" class="button1" id="create"
onclick="f1()">Create</button>
I need to get values of input A, B and amount, then pass them to url: "http://localhost:8080/dopayment/" with POST in xml format. The exact xml format must be:
<Payment>
<a>xxx</a>
<b>xxx</b>
<amount>xx</amount>
</Payment>
P.S from Postman I have checked above given XML with post to given URL, it is working.
Thanks in advance to everyone.
Since you create the form, put button into it to trigger submit event.
<form action="#" class="simple-form">
<input id="A" type="text" autocomplete="off">
<input id="B" type="text" autocomplete="off">
<input id="amount" type="text" autocomplete="off">
<input type="submit" align="middle" class="button1" value="Create">
</form>
You can sent info by AJAX, this way:
document.getElementsByClassName("simple-form")[0].addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const data = `<Payment>
<a>${formData.get('A')}</a>
<b>${formData.get('B')}</b>
<amount>${formData.get('amount')}</amount>
</Payment>`;
fetch('http://example.com', {
method: 'POST', // or 'PUT'
body: data, // data can be `string` or {object}!
headers:{
'Content-Type': 'application/xml'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
});
I have a form as so, which submits data to an outside domain:
<form action="https://EXTERNALdomain.com/register" id="form_register" method="POST">
<input type="text" id="first-name" name="first-name" value="" placeholder="First Name" required/>
<input type="text" id="last-name" name="last-name" value="" placeholder="Last Name" required/>
<input type="email" id="email" value="" name="email" placeholder="Email Address" required/>
<input type="password" id="password" name="password" placeholder="Password" required/>
<input type="submit" value="Create Account" />
</form>
However, I'm trying to be able to submit the form AND redirect it to a different page, also externally. So far, my attempts have been unsuccessful with AJAX.
<script type="text/javascript">
function sform() {
$.ajax({
url: "https://EXTERNALdomain.com/home",
data: $('#request').serialize(),
type: 'POST',
success: function (resp) {
alert(resp);
},
error: function(e) {
alert('Error: '+e);
}
});
}
I've then been calling the form as so:
<form onsubmit="sform()" id="request">
This isn't working. I just get a long URL, and the form doesn't actually post, the page just reloads
This is because you're letting the form submit, which changes the page url and POSTs data there.
From "submit the form AND redirect it to a different page" I assume you want to submit the form to https://EXTERNALdomain.com/register and redirect to https://EXTERNALdomain.com/home. To do this, you need to use $.ajax to submit the form, them change the location on success.
function sform() {
$.ajax({
url: $('#request').attr("action"),
data: $('#request').serialize(),
type: $('#request').attr("method"),
success: function (resp) {
location.href = "https://EXTERNALdomain.com/home"; // redirect
},
error: function(e) {
alert('Error: '+e);
}
});
return false; // cancel default action
}
I have a form as follows:
<form name="signupForm" id="signupForm" method="POST" ng-submit="create()">
<input type="hidden" name="username" id="username" value="mtest">
<input type="text" placeholder="Account name" name="webid" ng-model="account.webid" ng-focus="isFocused" ng-blur="isFocused = false"><br>
<input type="text" placeholder="Full name" name="name" ng-model="account.name"><br>
<input type="text" placeholder="Email" name="email" ng-model="email"><br>
<input type="text" placeholder="Picture URL" name="pictureURL" ng-model="account.pictureURL"><br>
<keygen id="spkac" name="spkac" challenge="randomchars" keytype="rsa" form="signupForm" hidden>
<br>
<input type="submit" id="submit" value="Submit">
</form>
The data is passed to the POST as follows:
$http({
method: 'POST',
url: uri,
data: $("#signupForm").serialize(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/x-x509-user-cert'
},
withCredentials: true
}).
Once I submit the form to send it with a POST http request, I get the $("#signupForm").serialize() as follows:
"username=mtest&webid=mtest.databox.me%2Fprofile%2Fcard%23me&name=M+Test&email=mtest%40test.com&pictureURL=picURL&spkac="
Why is the keygen element always empty? Is there anything wrong I am doing?
Any answer is appreciated, thanks in advance.
Solved!
So preparing an HTTP Request to do that doesn't work for some reason. Instead the form action needs to be set and form submitted straight away in order to send the keygen with it. Here the solution:
in the Template the action is parametrical:
<form name="signupForm" id="signupForm" method="POST" action="{{actionUrl}}">
...
<input type="submit" id="btnSubmit" value="Submit" ng-click="completeForm()">
and the Controller sets the action and submits the form as follows:
$scope.completeForm = function () {
$scope.actionUrl = "https://" + document.getElementById("username").value + "...";
document.getElementById("signupForm").submit();
};
I have two forms, one for uploading a file and another for filling the form with information. I need to upload the file without refreshing the page first and then submit the form using ajax. And here are the codes:
form_file
<h1>Insert Employee</h1>
<form id="form">
<input id="name" placeholder="arabic name.." type="text" name="name_ar"/><br>
<input id="name" placeholder="english name.." type="text" name="name_en" value=""/><br>
<input id="name" placeholder="arabic department.." type="text" name="dep_ar" /><br>
<input id="name" placeholder="english department.." type="text" name="dep_en" /><br>
<input id="name" placeholder="arabic job.." type="text" name="job_ar"/><br>
<input id="name" placeholder="english job.." type="text" name="job_en" /><br>
<input id="name" placeholder="extention#.." type="text" name="ext" /><br>
<input id="name" placeholder="office#.." type="text" name="office" /><br>
<input id="name" placeholder="mobile#.." type="text" name="mobile" /><br>
<input id="email" placeholder="email" type="text" name="email"/><br>
<br /><br />
<div class="upload_form">
<form id='form1'>
<input type="file" name="userfile" size="20" />
<input type="button" value="upload" id="upload" />
</form>
<br/><br/>
</div>
<input type="button" value="Click" id="submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
AND HERE IS THE AJAX: I know how to submit data using ajax but I need help for how to upload a file using ajax without refreshing the page, and then take the name of that file, send it again with the form, and save it to database.
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload was clicked');
//ajax POST
$.ajax({
url:'upload/do_upload',
type: 'POST',
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#uploud_form').empty();
$('#uploud_form').append(msg);
}
});
return false;
});
$('#submit').click(function(){
console.log('submit was clicked');
//empty msg value
//$('#msg').empty();
//Take form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
//ajax POST
$.ajax({
url:'',
type: 'POST',
data: form_data,
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#contact_form').empty();
$('#contact_form').append(msg);
}
});
return false;
});
});
</script>
Not sure whether I get it properly or not. I will try to answer as per my understanding.
You need to write server side code which will save the image on server.
I believe you are able to make the AJAX call to initiate point 1.
From your upload service (point 1), your should return the "relative path" of the image which was uploaded.
In success callback of your AJAX call (point 2) you should be able to capture the relative path.
Once the relative path has been captured you should add it to DOM or say any element.
Then you can start another AJAX call or post back (submit form) based on your requirement.
If this is not the problem then please be specific in what you need and provide more information.
I do it like this and it's work for me :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>