user6224087
user6224087

Reputation:

Insert file names into database with AJAX

I am using a photo upload script which can be found at https://github.com/CreativeDream/php-uploader

I want to insert the file names into database as a comma separated value. But since this uploader is using a drag and drop div to upload files it not holding the values in <input type="file" name="files[]" id="filer_input2" multiple="multiple">.

HTML:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server">
      <textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
      <div class="media"><input type="file" name="files[]" id="filer_input2" multiple="multiple"></div>
      <input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>

Jquery and Ajax:

$(function() {
    $("#submit").click(function() {
        var textcontent = $(".newstatuscontent").val();
        var mediafile = $(".mediafile").val();
        console.log('media files: ' + mediafile);
        var dataString = 'content='+ textcontent;
        if(mediafile == ''){
            if(textcontent == ''){
                $('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
            }
        }else{
            $.ajax({
                type: "POST",
                url: "post-status.php",
                data: dataString,
                cache: true,
                success: function(html){
                    $("#shownewstatus").after(html);
                    $(".newstatuscontent").val('');
                }  
            });
        }
        return false;
    });
});

PHP image upload file:

<?php
    include('class.uploader.php');

    $uploader = new Uploader();
    $data = $uploader->upload($_FILES['files'], array(
        'limit' => 10, //Maximum Limit of files. {null, Number}
        'maxSize' => 10, //Maximum Size of files {null, Number(in MB's)}
        'extensions' => null, //Whitelist for file extension. {null, Array(ex: array('jpg', 'png'))}
        'required' => false, //Minimum one file is required for upload {Boolean}
        'uploadDir' => '../uploads/', //Upload directory {String}
        'title' =>  array('{{random}}{{.extension}}', 32), //New file name {null, String, Array} *please read documentation in README.md
        'removeFiles' => true, //Enable file exclusion {Boolean(extra for jQuery.filer), String($_POST field name containing json data with file names)}
        'replace' => false, //Replace the file if it already exists  {Boolean}
        'perms' => null, //Uploaded file permisions {null, Number}
        'onCheck' => null, //A callback function name to be called by checking a file for errors (must return an array) | ($file) | Callback
        'onError' => null, //A callback function name to be called if an error occured (must return an array) | ($errors, $file) | Callback
        'onSuccess' => null, //A callback function name to be called if all files were successfully uploaded | ($files, $metas) | Callback
        'onUpload' => null, //A callback function name to be called if all files were successfully uploaded (must return an array) | ($file) | Callback
        'onComplete' => null, //A callback function name to be called when upload is complete | ($file) | Callback
        'onRemove' => null //A callback function name to be called by removing files (must return an array) | ($removed_files) | Callback
    ));

    if($data['isComplete']){
        $files = $data['data'];

        echo json_encode($files['metas'][0]['name']);
    }

    if($data['hasErrors']){
        $errors = $data['errors'];
        echo json_encode($errors);
    }

    exit;
?>

In console I am getting the value as UNDEFINED. Please view the script and help me solve the issue. I want to get the file names in var mediafile = $(".mediafile").val(); so that I can transfer it to my upload script in a comma separated value. Also please let me know whether the values should be imploded as comma separated values before transferring the data to the php file via ajax, or else I can implode it later in the php file or not.

Upvotes: 2

Views: 982

Answers (1)

DominicValenciana
DominicValenciana

Reputation: 1731

How get and parse a file name

Bellow is a working example I made to show you how to grab a file name.

First thing I did was listen to see if the file input changes. When it does it will grab the files associated with the input and loop through them all. I concatenate the names in to one string delimited by semicolons and set the value of .mediafile to the concatenated file names.

$('#filer_input2').change(function(){
    var files = $(this)[0].files;
var output = "";
for (var i = 0; i < files.length; i++) {
    console.log(files[i].name);
    output += files[i].name+";";
}

$(".mediafile").val(output);

});

Fiddle: https://jsfiddle.net/56gdke45/

Upvotes: 1

Related Questions