Hell guys I been searching online for a while on uploading files with JavaScript and I ran into good sites especially this one https://developer.mozilla.org/en-US/docs/Web/API/FormData ,so I have this script that uploads an image with ajax with jQuery to the server so I want to know how I can convert this into a jQuery structure instead. I'm not a big fan with the document.getElementById
and the .files[0]
structure.
Here is my code
index.php
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('button').click(function(){
var form_data = new FormData();
form_data.append('file', document.getElementById('file').files[0]);//<-Convert this section into a jQuery structure
//Success variable
var success= function(result){
$('.output').html(result);
}
//Error variable
var error= function(result){
alert(error);
}
//Request
$.ajax({
url:'x.php',
method:'POST',
data: form_data,
contentType: false,
processData: false,
success: success,
error: error
});
});
});
</script>
<input type='file' id='file'/>
<button>Send</button>
<div class='output'></div>
x.php
<?php
//Db credentials
$db_servername = 'localhost';
$db_username = 'sb';
$db_password = '1234';
$db_name = 'test';
//
$db_connect = new mysqli($db_servername, $db_username, $db_password, $db_name);
//Upload components structure
if($_FILES['file']['name'] != '')
{
$test = explode('.', $_FILES['file']['name']);
$ext = end($test);
$prefix= 'random';
$file_name = $prefix . uniqid() . '.' . $ext;
$directory = 'images/';
$location = $directory.$file_name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
}
//
$db_query= "INSERT INTO ajax_image_upload (image_name) VALUES ('$location')";
$db_result = $db_connect->query($db_query);
?>
<style>
#order{
display: inline-block;
margin-top: 50px;
}
#uploaded-image{
display: block;
width: 150px;
height: 150px;
}
#location-label{
display: inline-block;
font-weight: 600;
}
#location-value{
display: inline-block;
}
</style>
<p id='order'>Image 1</p>
<img id='uploaded-image' src='<?php echo $location; ?>'/>
<p id='location-label'>Location:</p><em id='location-value'><?php echo $location; ?></em>