XMLHttpRequest & FormData not submitting data - javascript

I am trying to submit a form via ajax using the post method and a FormData object.
Here is a simplified version of the JavaScript:
var form=…; // form element
var url=…; // action
form['update'].onclick=function(event) { // button name="update"
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
};
The form has:
a button (type="button" name="update") to run the script
no action and method="get"
My PHP script has the following:
if(isset($_POST['update'])) {
print_r($_POST);
exit;
}
// more stuff
print 'other stuff';
When I try it, the PHP falls through to the rest of the code, and I get the other output, rather than what I expect from the print_r statement.
I have tried the following variations:
new FormData() (without the form). This does work if I add the update data manually.
new FormData(form). This does not work, whether I add the update manually or not.
changing the form method to post.
Firefox, Safari & Chrome on MacOS; all current versions.
The from itself looks something like this:
<form id="edit" method="post" action="">
<p><label for="edit-summary">Summary</label><input id="edit-summary" name="summary" type="text"></p>
<p><label for="edit-description">Description</label><input id="edit-description" name="description" type="text"></p>
<p><label for="edit-ref">Reference</label><input id="edit-ref" name="ref" type="text"></p>
<p><label for="edit-location">Location</label><input id="edit-location" name="location" type="text"></p>
<p><button type="button" name="update">OK</button></p>
</form>
What should I do to submit the get this to work?
No jQuery, please.

The content type when sending a FormData object is multipart/form-data not url encoded.
Further more the proper boundary must be set for the request, which the user is unable to do. For this XMLHttpRequest sets the correct content type with the required boundary.
So all you have to do is not set the content type and it'll work.
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");<--don't do this
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};

Change the name of the button to something other than "update" (and change it in your form['update'].onclick... as well). I think its clashing with the value you are trying to set on the FormData to trigger the PHP code.

Related

Send single hidden field with form using javascript

Currently I'm working with ASP.Net and a nested form. My problem is,
that ASP.Net only allows one form per page, but I need a kind of sub-form
to redirect to another page.
My idea was to create a submit using JavaScript, but I don't get how to set the
content of the post, which will be send.
For example I've tried to use the following code:
<div>
<input type="hidden" value="ABCDE" />
<input title="Send Form" onclick="this.form.method = 'post'; this.form.action = 'https://externpage/url'; this.form.submit();" type="submit" />
</div>
My problem is, that the content of the request should only be the hidden fields containing ABCDE and not all fields on the page. How can i achieve this using JavaScript and HTML?
Thanks a lot!
Use FormData() to do the encoding.
sendForm=(e)=>{
let data = new FormData();
let hidden = document.querySelector('button').parentNode.firstChild.value;
data.append('hidden',hidden);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=()=>(xhr.readyState == 4) ? console.log(xhr.response) : null;
xhr.open('POST','http://yoururl.com');
xhr.send(data);
}
document.addEventListener('DOMContentLoaded',()=>{
document.querySelector('button').addEventListener('click',sendForm);
});

Chrome Extension: How to send html form data to a php page upon button being clicked which redirects to said php page

so i have a chrome extension which has a form popup which contains butttons and editable fields which are autopopulated by my javascript functions and options page. It has the ability to send the form data to a php page 'PhpFile.php', upon clicking a button, which then inserts the data in a database using a query.
I also have another php page DataDisplayScript.php. This page is intended to display specific records in the database which match certain fields in the users form such as age and gender. At the minute i have a button on the chrome extension with some javascript called by it which takes me to this page but so far i can only get the page to load the whole data table when redirected to it. This is because it doesnt have any information about the user from the form.
My question is if its possible for when i click the button on my extension which redirects me to the DataDisplayScript can i send certain field values from the form to the php page? which i can then use to query the database for the matching records and display them on the page. (dont really need help with the query, just with sending the data upon the user clicking a button or a link).
Here is my html for the form involved in sending user information to DataDisplayScript.php
<form action="http://************/DataDisplayScript.php" method="POST" name="HiddenUIDPostForm">
<input type = "text" id="UIDSuggestions" name="UIDSuggestions" hidden="true">
<input type="text" id="Gender" name="Gender" placeholder="Your Gender"><br/>
<input type="text" id="Age" name="Age" placeholder="Your Age"><br/>
<input type = "submit" name="uidSubmit" value="Go To Suggestions">
</form>
Here is my javascript for the button which redirects me to the DataDisplay script page:
function ClickSuggestionsLink(data){
/*if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","DataDisplayScript.php",true);
xmlhttp.send();
*/
chrome.tabs.create({url: 'http://***********/DataDisplayScript.php'});
}
Here is my php on DataDisplayScript which id like to store the form info sent
$uId = $_POST['UIDSuggestions'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
Any help would be greatly appreciated!
This should help. AJAX with Post method.
function ClickSuggestionsLink(data){
var dir = 'http://***********/DataDisplayScript.php';
var request = new XMLHttpRequest();
var uId = document.getElementById("UIDSuggestions").value;
var gender = document.getElementById("Gender").value;
var age = document.getElementById("Age").value;
var data = "UIDSuggestions="+uId +"&Gender="+gender+"&Age="+age;
request.open("POST", dir, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", data.length);
request.setRequestHeader("Connection", "close");
request.onload = function() {
if (request.status === 200) {
// code if everything went fine
// request.responseText for printing echoes
} else {
// code if otherwise
}
};
// sending data here
request.send(data);
}

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

How to have javascript fill out and submit a form on another webpage

I have a website that manages where people are and what they are doing at work and if they need help or not.
I am using phone gap in order to make my application and I was wondering if it is possible to take a button on the phone gap and have javascript fill out a form on my webpage and then submit it so I can then process that data?
The form that I am trying to connect to is. I process this form in python through flask:
<form action="" method="POST" id = "stuff">
<dl>
<dt>
<input type=text name=gc>
<input type=text name=cursquad>
<input type=text name=trap>
<input type=text name=scrtkey>
<input type="submit">
</form>
You could use an AJAX post request with jquery, but then you'll need jquery in your phonegap, which might be quite overkill only for this.
Therefor I'd recommend this approach:
<script>
function loadXMLDoc() {
var url = "http://example.com";
var parameters = "foo=bar&bar=baz"; // Construct you form values like field=value&field2=value2&...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
</script>
This will POST all the data you put into parameters to the url you give. If you point it to your form page it should work.
If it doesn't, (jquery approach doesn't work out of the box), you might have to add some headers to the receiving page to allow it to receive data from external pages. The Access-Control-Allow-Origin header is needed here, where you can provide a list of safe domains. Since your application is not on a domain though, you could add this to your receiving page (Assuming you are running php):
header('Access-Control-Allow-Origin: *');
Try running it without first though, as it opens your form for everyone.

Submit form and stay on same page?

I have a form that looks like this
<form action="receiver.pl" method="post">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
and I would like to stay on the same page, when Submit is clicked, but still have receiver.pl executed.
How should that be done?
99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...
You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.
<style>
.hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>
<iframe name="hiddenFrame" class="hide"></iframe>
<form action="receiver.pl" method="post" target="hiddenFrame">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...
gracefully handle errors (e.g. retry)
provide UI indicators (e.g. loading, processing, success, failure)
run logic before the request is sent, or run logic after the response is received.
The easiest answer: jQuery. Do something like this:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
If you want to add content dynamically and still need it to work, and also with more than one form, you can do this:
$('form').live('submit', function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
The HTTP/CGI way to do this would be for your program to return an HTTP status code of 204 (No Content).
When you hit on the submit button, the page is sent to the server.
If you want to send it async, you can do it with ajax.
Use XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);

Categories