How to send data to server with javascript - javascript

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.

Related

GET https://localhost/fetch/doc.xml 404 (Not Found)

Good evening, I am a beginner, I am on an application where the client has to download one of the xml files, but when the file is in local folder it downloads it and when it is elsewhere, it says:
GET https://localhost/dossier/data.xml 404 (Not Found).
How to make it accept the file no matter where it is?
This is the code:
<form id="parcourir">
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">Parcourir</button> <br>
<span id="custom-text">Aucun fichier selectionné</span>
</form>
<script>
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
})
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1];
console.log(location.href);
console.log(customTxt.innerHTML);
myFunction(this);
} else {
customTxt.innerHTML = "no file choosen yet";
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", customTxt.innerHTML, true);
xhttp.onload = (response) => {
console.log(xhttp.response);
}
xhttp.send();
})
function myFunction(xml) {
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
}
</script>

How to upload a file using javascript?

I want to create an uploader with js. Can anyone help me how to upload a file using javascript?
You can use html5 file type like this:
<input type="file" id="myFile">
You file will be in value:
var myUploadedFile = document.getElementById("myFile").files[0];
For more information see https://www.w3schools.com/jsref/dom_obj_fileupload.asp
and see example here: https://www.script-tutorials.com/pure-html5-file-upload/
You can upload files with XMLHttpRequest and FormData. The example below shows how to upload a newly selected file(s).
<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {
const fd = new FormData();
// add all selected files
e.target.files.forEach((file) => {
fd.append(e.target.name, file, file.name);
});
// create the request
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
// we done!
}
};
// path to server would be where you'd normally post the form to
xhr.open('POST', '/path/to/server', true);
xhr.send(fd);
});
</script>
HTML Part:
<form enctype = "multipart/form-data" onsubmit="return false;" >
<input id="file" type="file" name="static_file" />
<button id="upload-button" onclick="uploadFile(this.form)"> Upload </button>
</form>
JavaScript Part:
function uploadFile(form){
const formData = new FormData(form);
var oOutput = document.getElementById("static_file_response")
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload_static_file", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
console.log(oReq.response)
} else {
oOutput.innerHTML = "Error occurred when trying to upload your file.<br \/>";
}
};
oOutput.innerHTML = "Sending file!";
console.log("Sending file!")
oReq.send(formData);
}
In the above HTML, I'm using the form to capture the files and calling the JS function when the button is clicked. In the JS function, I'm using the XMLHttpRequest to send the file.
A detailed step-by-step document can be found here.

Uploading with AJAX not working, form data empty

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

image upload using javascript?

This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}

Submit multiple values of a form using AJAX (but no jQuery) - XMLHttpRequest

Normally I'd use jQuery for this, but to cut a long story short, on this I can't.
I've successfully submitted a form via AJAX which has only one element of a form, like this:
<div id="response"></div>
<form onsubmit="submitStuff(this.datatosend.value);this.reset();return false;">
<input id="datatosend" type="text" />
<input type="submit" />
</form>
<script>
function submitStuff(e) {
if (e == "") {
document.getElementById("response").innerHTML = "";
return
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText
}
};
xmlhttp.open("GET", "sumbitData.php?data=" + e, true);
xmlhttp.send()
}
</script>
Now say I have this form:
<form onsubmit="????????????????????;this.reset();return false;">
<input id="datatosend1" type="text" />
<input id="datatosend2" type="text" />
<input type="submit" />
</form>
How do I do the same, submitting both values?
I'm a bit new to Javascript, especially 'pure' Javascript so please be a bit patient!
Build up the string
var data1 = encodeURIComponent(document.getElementById("datatosend1").value);
var data2 = encodeURIComponent(document.getElementById("datatosend2").value);
var url = "sumbitData.php?data1=" + data1 + "&data2=" + data2;
Read the form values and make a string to attach to the url:
var child=document.getElementById(form_id).getElementsByTagName('input');
var data=new Array();
for(var i=0;i<child.length;i++){
data.push(child[i].id + '='+ encodeURIComponent(child[i].value));
}
data='?' + data.join('&');

Categories