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();
};
Related
What I am trying here is when you click on submit button I am calling one javascript function which takes all the form element values and passes it to the php page without storing them inside the variable and then send those variables.
Example of my form:
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" onsubmit="sendvalues()" value="Stash the file!" />
</form>
Now on javascript, I want to send userid and email fields to directly go to php page without first retrieving them into a variable and then send that variable via ajax.
function sendValues() {
var formElement = document.querySelector("form");
console.log(formElement);
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "<?php echo VIEW_HOST_PATH;?>process_data.php");
formData.append("process_type", 'process_data');
request.send(formData); //want to send all form userid, email directly to php page
request.onreadystatechange = (e) => {
console.log(request.responseText)
}
}
Is this possible to send user_id and email values to php page directly? So, for example, form element which contains emailed and user info and any other forms element and they all send to php page via ajax but most important without storing this element values in javascript variables.
thanks
In your form you should specify property "action". That action would be your php file that will handle your submit action. Also you could add to this form id selector.
<form id="file-info" enctype="multipart/form-data" action="/process_data.php" method="post" name="fileinfo">
And now in your function sendValues() you could submit form like this:
function sendValues() {
document.getElementById("file-info").submit();
}
or you do not even need this function if you set your input button type to submit:
<input type="submit" name="submit" />
And then in your php file you can use your variables like:
if (isset( $_POST['submit']))
{
$userId = $_POST['userid'];
$email = $_POST['email'];
}
Try this one then
HTML CODE
<form enctype="multipart/form-data" method="post" class='submit_form' name="fileinfo">
<label>Your user name:</label>
<input type="text" name="name" id='name' placeholder="name" required /><br />
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" id='userid' placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" value="Stash the file!" class='submit' />
JQUERY CODE on the same page (include jquery)
$('body').on('click', '.submit', function(e) {
e.preventDefault();
$.ajax({
'url': 'mpay.php',
'type': 'POST',
'data': $('.submit_form').serialize(),
success: function(response) {
console.log(response);
}
});
});
PHP CODE The file name is mpay.php
$arr = [
'name' => $_POST['name'],
'email' => $_POST['email'],
];
echo "<pre>;
print_r($arr);
echo "</pre>";
Hope this helps.
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));
});
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>
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 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>