0

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>
Maak
  • 3,791
  • 2
  • 21
  • 35
  • 1
    How exactly is it not working for you ? because from the looks of your javascript code, it looks ok, just as suggested by https://stackoverflow.com/a/21045034/614277 – Abderrahmane TAHRI JOUTI Apr 22 '18 at 10:06
  • https://stackoverflow.com/a/19544554/6647153 – ibrahim mahrir Apr 22 '18 at 10:09
  • Sorry abderranmane I thought it was a post I saw already i'm looking at it right now give me a moment :-). –  Apr 22 '18 at 10:10
  • Sorry @AbderrahmaneTAHRIJOUTI I thought I saw that post already but clearly I did not see it I need to be more careful of unintentional duplicate posts I did not mean to but thank you for linking me to a post I did not saw. –  Apr 22 '18 at 10:20

1 Answers1

0

Simplest way is pass a form element into FormData(). There is no need to use append() doing it this way

If you do it inside a submit event handler you can pass in this which is the form

<form id="myForm">
   <input type='file' id='file'/>
   <button>Send</button>
</form>

jQuery

$(document).ready(function() {

  $('myForm').submit(function(event) {
    // prevent browser default submit process
    event.preventDefault();

    // "this" is the form element
    var form_data = new FormData(this);

    //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
    });
  });
});
charlietfl
  • 164,229
  • 13
  • 110
  • 143