Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I know there is posts online already that covers this subject but most examples are based on jQuery and I need to do this in plain JavaScript. I found a few rare JavaScript examples on this

subject online but I can't manage to get it working in my code structure. If any one can give me a code example of my code then I will really appreciate that.

This is my code.

index.php

<style>

#photo-input{
display: block;
margin-bottom: 50px;
}

</style>

<script>

document.addEventListener('DOMContentLoaded',function(){

document.querySelector('#submit').addEventListener('click',sendUploadInfo);

function sendUploadInfo(){

var photo= document.querySelector('#photo-input').files[0];

//<JSON data>

var upload_info = {
    first_name: "John",
    last_name: "Smith",
    photo: photo
};

//</JSON data>

var upload_info_json_object= 'upload_info_json_object='+JSON.stringify(upload_info); 

//<AJAX>
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){

if(xhr.readyState == 4){

document.querySelector('#output').innerHTML= xhr.responseText;

}
}

xhr.open('POST','x');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(upload_info_json_object);
//</AJAX>
}

});

</script>

<input type='file' id='photo-input'>

<button id='submit'>Send JSON data</button>

<div id='output'></div>


x.php

<?php

$upload_info_json_object = json_decode($_POST['upload_info_json_object']);

$first_name= $upload_info_json_object->first_name;
$last_name= $upload_info_json_object->last_name;


//Photo upload section
//$photo= $upload_info_json_object->photo; //<-????
///???

if(isset($_FILES['photo'])) {
$file=$_FILES['photo']['name'];
$location='images/'.$file;
move_uploaded_file($_FILES['photo']['tmp_name'],$location); 
}
//

?>

<h1><?php echo $first_name.' '.$last_name.' just uploaded a photo.'; ?></h1>


What I have tried:

Went to other help sites and no luck and no luck with google.
Posted
Updated 16-Jul-19 7:24am

1 solution

You cannot upload a file as part of a JSON document. That's not how HTML file uploads work.

To upload a file via AJAX, you'll need to use the FormData class[^]. Your form values will then be available on the server via the usual $_POST and $_FILES collections.

Sending files using a FormData object | Using FormData Objects - Web APIs | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900