I am trying to create form data to send within a post request (to a PHP script) with FormData.
However, the FormData object is always empty:
var oReq = new XMLHttpRequest();
var url = "http://www.test.com/test.php";
oReq.open("POST", url, true);
oReq.setRequestHeader("Content-Type","multipart/form-data");
var myFormData = new FormData();
myFormData.append("formType","PDF");
myFormData.append("pdf", pdf.output(),"thisPDF.pdf");
oReq.send(myFormData);
the 'pdf' variable is a jsPDF object (I've checked that it is a valid object and I have tried to remove that line and only have the "test" form data element sent. Yet, myFormData is always an empty object. Hoping I'm just missing something simple here.
In addition, when I try to check for the existence of the form elements in the PHP script, it shows no $_POST and no $_FILE elements at all.
ADDITIONAL INFO:
When I try this code:
var oReq = new XMLHttpRequest();
var url = "http://www.test.com/test.php";
oReq.open("POST", url, true);
oReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var myFormData = new FormData();
myFormData.append("formType","PDF");
alert(JSON.stringify(myFormData));
oReq.send(myFormData);
I can then access the "formType" $_POST variable in the php script. But if I add in the File append statement to the myFormData object (and keep the same 'Content-Type', the PHP script errors returning a "not allowed access" error.
However, the $_POST is set according to isset($_POST) in both cases and with the file inserted the $_FILE variable is set according to isset($_FILE).
Remove the oReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); from the code. Browser automatically set multipart/form-data header, if you add file in FormData.
Related
I'm trying to save a post request data to a google spreadsheet. However, the data is saved as undefined.
The original post uses a form and uses jquery. See the link below. But I'm trying to pass an array also without the use of jquery.
I'm using the following app script without using jquery - https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
I'm posting the code here.
function sendData(data) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "spreadsheeturl";
xmlhttp.open("post", theUrl);
//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send(JSON.stringify(data))
}
I found the answer, you have to uncomment a block in the app script if you are passing JSON data.
I tried multiple approaches and followed quite a lot questions in StkOvfl, and W3 Specifications, but still no idea.
I have a form input:
<input type="file" multiple accept="image/*" id="item-image-upload" >
Then in my Javascript (prepareFormData method): [See full gist class here]:
var files = this.getFiles();
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
continue;
}
formData.append(this.uploadEntityName, file);
}
When I console.log(files), I get all the files all fine. But, formData is not working. I also tried adding an arbitrary item as:
formData.append("Apple", 1);
The response I get is empty. The server does repose in php as:
public function uploadImage(){
return json_encode(array_merge($_REQUEST, $_FILES));
}
I'm 99% sure now that it's your header, and that if you look in your logs, or turn on PHP Warnings you'll see Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0
I copied this (and added your header line and removed the input file) from MDN and ran it on a script on my dev box that is set to shout all errors and I got that error, followed by an empty array
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"
// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("somefiles[]", blob);
var request = new XMLHttpRequest();
request.open("POST", "MYDEVBOX/testpost.php");
// remove the line below and it works
request.setRequestHeader("Content-Type", "multipart/form-data");
request.responseType = "json";
request.send(formData);
Back a few minutes later after deciding to look into why. It has to do with the boundary of the multi-part data. The XHR is automatically setting the header with matching boundary when you do xhr.send(formData) (or somewhere along the way). When you set that header, the request uses that instead, wiping out the boundary and PHP doesn't know where to split the input. Here's a quick screen cap that points it out much better.
I'm working on form submission with AJAX but using plain JavaScript, no external libraries.
I've been having a problem when it comes to parsing the form as the PHP doesn't seem to be parsing the data correctly.
From some research on the internet, I've seen people set the content type to "false". The problem is however, they are are using JQuery to do this and I'm not sure how I do this in plain JavaScript.
I am only submitting a file and my PHP processes forms uploaded the traditional way perfectly.
The AJAX also seems to work flawlessly and I see no fault in the code. Here is my upload function.
var fd = new FormData();
fd.append("upload-file", document.getElementById('upload-file').files[0]);
var xhr = new XMLHttpRequest();
/* I add some event listeners here for progress, load, error, and abort */
xhr.open("POST", "upload.php");
xhr.send(fd);
In order to set the content type you need to modify the request header.
I don't know which content type you'd like to set, so I've defaulted to json.
Here's how you can set it:
var fd = new FormData();
fd.append("upload-file", document.getElementById('upload-file').files[0]);
var xhr = new XMLHttpRequest();
/* I add some event listeners here for progress, load, error, and abort */
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Content-type","application/json");
xhr.send(fd);
EDIT: Setting HTTP request headers from MDN
When an HTML form contains <input type="file"> I need to specify the enctype="multipart/form-data" attribute on the form. However, when I send a binary file over XMLHttpRequest I don't need to specify that type anywhere:
var builder = new BlobBuilder();
builder.append("Hello world!");
var blob = builder.getBlob("text/plain");
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.send(blob);
Why so?
With a form, you are telling the browser how to format the data to send it to the server. (The default value for enctype doesn't support files).
With XHR, you are formatting the data yourself. (That said, you should still use addHeader to specify a suitable content-type for your POST body).
All I'm trying to do is send a string, in html, to a script written in PHP. I've tried several solutions, including making an html element and putting it in a form and then passing the form (didn't work). I don't know the basics of AJAX or PHP, everything is just kind of being pieced together via what I can google. Here's one way I trying to remedy the situation: (The regexp replaces the first line of the file, which I works. I tried foreach loops with assigning a variable to $_POST[$key], I tried sending just the string with html hoping that would work. I believe the problem lies in the HTML, or in the AJAX call, because I can make the form submit() to the .php file and then it works, however, that would change the browser location to that file and obviously with AJAX, that's not what I want. Anyone have any ideas (other than JQuery syntax)?
HTML
<form>
<input type="hidden" name="test" id="test" value="testString">
</form>
JavaScript AJAX call
function sendString()
{
var data = document.getElementById("test");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'testing.php', true);
xhr.send(data);
}
PHP File
<?php
$line = $_POST['data'];
$file = 'test.txt';
file_put_contents($file,preg_replace('/^.+/',$line,file_get_contents($file),1));
?>
EDIT: Thanks for the responses, but non have worked. I tried:
document.getElementById("test");
document.getElementById("test").value;
and
xhr.send(data.value);
None of these worked. Still Blank lines. I also tried the extended solution.
Your problem is here:
var data = document.getElementById("test");
You're creating a reference to your html element. You need to reference the value property of your element.
var data = document.getElementById("test").value;
Also, you are only sending the value and not a key value pair to the server. So xhr.send(data); will only send the value. Your PHP script won't know that $_POST['data'] is what you mean. You need to format var data as
var data = "data=" + document.getElementById("test").value;
EDIT
To send form data via POST, you may need to add some header information.
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
// change your function
function sendString()
{
var data = "data="+document.getElementById("test").value;
var xhr= new XMLHttpRequest();
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
In testing.php you can call them via $_POST:
echo $_POST['data'];
Example here: http://www.openjs.com/scripts/examples/ajax_using_post.php