POST XML to web service with javascript - javascript

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

Related

POST request Fetch API prevent redirect

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>

<keygen> element empty in POST after form submit

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

ajax upload file form

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>

Cannot process the data send by FormData in a PHP server

I'm using FormData to send the content of a form but it seems I can't get my script running well. It send something to the server (PHP), but on the server nothing is received and it returns an empty array.
Note: I am not using jQuery
I have a form:
<form id="main_form" name="main_form" enctype="multipart/form-data">
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input class="submit" value="Click Here!" name="submit" type="submit"><br>
</form>
I sent it with Javascript XMLHttpRequest Object:
Ajax.send(new FormData(document.getElementById("main_form")));
I put here the FireBug Info:
Params:
-----------------------------19926109411601--
Response:
// using the following
print_r($_REQUEST);
print_r(file_get_contents("php://input"));
// resposne
Array
(
)
-----------------------------139502076225657--
Request Headers:
Content-Type: application/json
Response Headers:
Content-Type: text/html
I also have tried another header than json, but to no avail:
application/x-www-form-urlencoded
How should I handle this?
I test with this and it works.
<form id="main_form" name="main_form" action="test2.php" enctype="multipart/form-data" method="post">
<input type="text" name="test1"><br>
<input type="text" name="test2"><br>
<input type="text" name="test3"><br>
<input class="submit" value="Click Here!" name="submit" type="submit"><br>
</form>
The result like this:
Array ( [test1] => asd [test2] => a [test3] => asd [submit] => Click Here! )
Best Regards
Regan

Javascript/AJAX - Sending a reverse image search request to google

so i've been trying to do a reverse image search request through ajax, and it's giving me 302 errors. looking at the firebug console, i found out that the url in the response header sent back by google is linking me to the results, but i have no idea how to access that and send another ajax query to the new location. any help would be appreciated!
this is the response header:
This is my current code:
<form action="http://images.google.com/searchbyimage/upload" id="contactForm1" method="post"
enctype="multipart/form-data">
<input type="hidden" name="image_url" id="image_url" />
<input type="hidden" name="btnG" id="btnG" value="Search" />
<input type="file" name="encoded_image" id="encoded_image" />
<input type="hidden" name="image_content" id="image_content" />
<input type="hidden" name="filename" id="filename" />
<input type="hidden" name="hl" id="hl" value="en" />
<input type="hidden" name="bih" id="bih" value="507" />
<input type="hidden" name="biw" id="biw" value="1920" />
<input type="button" name="submit" value="Submit" />
</form>
$(document).ready(function () {
$("form").bind("click", "input[type='button']", function () {
var formData = new FormData($("form")[0]);
$.ajax({
type: "post",
url: "http://images.google.com/searchbyimage/upload",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (text) {
console.log(text);
}
});
});
});
I think you should try with this:
var formData = new FormData($(this).closest("form").serialize());

Categories