I am trying to make upload work but for some reason the form data going to the server file is giving me empty
Form Code:
<form id="uploadxlsx" name="uploadxlsx" enctype="multipart/form-data">
<div class="form-group">
<label>Excel File:</label>
<input name="excelfile" id="excelfile" class="form-control" data-rule-required="true" data-msg-required="Choose File" type="file">
</div>
<div class="form-group">
<button type="button" name="submit" class="btn btn-primary" onclick="sendFile();">Upload</button>
</div>
</form>
the JS code for the above
var xhr, hUploadSpeed;
function sendFile()
{
document.getElementById("serverresponse").innerHTML = "";//clear previous server response
var url = "upload.cfm";
var formData = new FormData(document.getElementById("excelfile"));
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
alert(xhr.responseText);
document.getElementById("serverresponse").innerHTML = xhr.responseText;
}
}
xhr.send(formData); //Send to server
}
when the dump the server form scope, i get this
http://prntscr.com/gsjbtw
this is the request headers image
http://prntscr.com/gsjc3n
Related
I'm a good back dev, but have a huge problem at front. So, i have a form that download photo to send it to server.
<form name="Forma" id="photoForm" method="POST" enctype="multipart/form-data">
<input type="button" class="btn btn-secondary" name="btn_file" id="loadFileXml" value="Выбрать фото" onclick="document.getElementById('file').click();" />
<input type="file" id="file" style="display:none" name="photo" required accept="image/jpeg,image/png,image/gif " />
<button type="submit " class="btn btn-primary " hidden id="Test1">Проверить</button>
</form>
And here is a function that should send data to server, for getting JSON response (i'm not sure with it,
var fileuploadinit = function(){
$('#file').change(function(){
var pathwithfilename = $('#file').val();
var filename = pathwithfilename.substring(12);
console.log(this.value);
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').removeAttr("hidden");
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(file.files[0]);
});
};
$("#imgInp").change(function() {
readURL(this);
});
$(document).ready(function () {
fileuploadinit();
});
$('#file').on('change', function() {
if (this.value) {
console.log("Оппа, выбрали файл!");
console.log(this.value);
// $('#Test1').attr("disabled", "false")
$("#Test1").removeAttr("hidden");
$('#Test3123').attr("src", this.value);
$("#info").removeAttr("hidden");
} else { // Если после выбранного тыкнули еще раз, но дальше cancel
console.log("Файл не выбран");
}
})
var button = document.getElementById("Test1")
button.onclick = handleButtonClick;
function handleButtonClick() {
alert("Вы нажали на кнопку");
var xhr = new XMLHttpRequest();
var url = "/api/upload";
xhr.open("Post", url, true);
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.setRequestHeader("Access-Control-Allow-Origin", "url/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 & xhr.status == 200){
var json = JSON.parse(xhr.responseText);
console.log(json.name);
}
};
var data = new FormData(photoForm)
xhr.send(data);
}
So, i spent on it for like 2 days, and absolutely don't know how to get photo from form to server. i tried literally everything, i think. It works, then i use action at html form method.
This is the form:
<form id="login_form">
Login<br/>
user: <input id="login_user" name="login_user" type="text" /><br/>
pass: <input id="login_pass" name="login_pass" type="password" /><br/>
<input type="button" value="Submit" onclick="doStuff("login")" />
</form>
this is the js I used:
function doStuff(doWhat){
var sendString = new FormData(document.getElementById("login_form"));
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "?action="+doWhat, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
//do stuff
}
};
xmlhttp.send(sendString);
}
The PHP page only has echo var_dump($_POST);
If I send it like that it returns this, that I have no idea how to use:
D:\wamp64\www\test\index.php:18:
array (size=1)
'------WebKitFormBoundaryubX9lqZJrSEuJwB9
Content-Disposition:_form-data;_name' => string '"login_user"
admin
------WebKitFormBoundaryubX9lqZJrSEuJwB9
Content-Disposition: form-data; name="login_pass"
swordfish
------WebKitFormBoundaryubX9lqZJrSEuJwB9--
' (length=173)
If I try anything else, like using JSON.stringify() on the FormData before sending it or changing the content type from application/x-www-form-urlencoded to multipart/form-data it just returns an empty array. I should not use jQuery for this. Is there a way to send something usable or make the PHP page able to read it?
I have from like this:
<form id="form" method='post' action="http://192.168.1.33/api/" enctype="multipart/form-data">
<label>User login: </label>
<input type="text" id="userLogin"><br />
<label>User password</label>
<input type="text" id="userPass"><br /><br />
<label>Input command here</label>
<input type="text" size="100" placeholder="users" id="command" name="command"><br/><br />
<input type="file" name="file1"><br/>
<input type="file" name="file2"><br/>
<br />
<input type="submit">
</form>
<h3>Output: </h3>
<div id="output"></div>
And simple javascript code. This code gets form data (attached files) and creating 2 fields in http header with userName and userPass, and send it to my api:
<script type="application/javascript">
var myCommand = document.querySelector('#command');
document.forms[0].onsubmit = function (event) {
if (window.FormData) {
event.preventDefault();
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var url = form.getAttribute('action') + '?' + myCommand.value;
xhr.open('post', url);
xhr.setRequestHeader('x-auth-user', document.querySelector('#userLogin').value);
xhr.setRequestHeader('x-auth-pass', document.querySelector('#userPass').value);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// server response: xhr.responseText
document.querySelector('#output').innerHTML = this.responseText;
}
};
xhr.send(data);
}
};
(function() {
document.querySelector('#userLogin').value = "user1";
document.querySelector('#userPass').value = "user";
})();
</script>
How can I add json data in body request use javascript? Json like this:
{
"id":"",
"status":0,
"documentName":"user",
"documentDesctiption":"",
"documentAttachedUsers":"id, id, id"
}
In fact I don't need form. I need to send 1-n files and one json string in POST body.
Now Api (php) receives just only form data (files). I plan on getting the body like this:
$inputJSON = file_get_contents('php://input');
I'd like to upload image(s) via JavaScript (Non framework). Does anyone have a basic example of how to this?
I get this error message:
Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 Array ( )
Here is what I'm working with so far.
<form action="" method="" enctype="" id="uploadImage">
<input type="file" name="image1" id="image1" value="" >
<input type="button" id="submit_button" data-data_enctype="multipart/form-data" data-form_name="uploadImage" data-url="/gallery/images/upload/" data-change_div="getForm" value="Upload" onclick="image(this.id, form.id)"/>
</form>
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var datVar = document.getElementById(id);
var url = datVar.dataset.url;
var change_div = datVar.dataset.change_div;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById(change_div).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send('NULL');
You need to pass the data that you want to send to the xmlhttp.send() method. Currently you are passing it 'NULL' so it complains that the data is missing.
Something like
var data = document.getElementById('#uploadImage');
gets the form.
create a FormData object (FormData is only supported in modern browsers)
var formData = new FormData(data);
and then passing formData to the send method should do.
I am developing a web page and the purpose is to perform an http POST from form input elements, in JSON format. While the JSON element to be sent is formed properly, the request is never performed. Here is the code I have been using.
Form
<form id="input" action="javascript:snifForm()" >
User ID:
<input type="text" name="userId" id="userId" required>
Name:
<input type="text" name="name" id="name" required>
<div class="form-submit"><input type="submit" value="Submit" color="#ffffff" > </div></p>
</form>
Javascript (JSON.js, JSONRequest.js and JSONRequestError.js are imported)
<script type="text/javascript">
var requestNumber;
function snifForm()
{
var a1=document.getElementById("userId").value;
var a2=document.getElementById("name").value;
var toSend= {interactions: {id_user:a1, id_name:a2}};
var jToSend=JSON.stringify(toSend);
requestNumber = JSONRequest.post(
"http://someurl.com",
jToSend,
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
alert(value);
} else {
processError(exception);
}
}
);
alert(requestNumber);
}
</script>
I also tried the more classic form:
var xmlhttp = new XMLHttpRequest();
var out;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
out = xmlhttp.responseText;
alert(out);
}
else alert('nothing');
}
xmlhttp.open("POST", "the_same_url", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(jToSend);
After checking the server logs, no post is done ever :/
You should be attaching the event to the submit action of the form and you need to make sure to cancel the submit action.
I would not add the events directly to the form, but it is
<form id="input" onsubmit="snifForm(); return false;">