2

I got a php file that saves file to server to a folder called upload it receives file via an ajax request every thing works fine so far the next requirement is to send a string along with the file to specify an upload folder & sub folder like "Course/Math" how to achieve that?

JS

$( document ).ready(function() {
$('#Upload').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'uploadFile.php',  
        type: 'POST',
        xhr: function() {  
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ 
                myXhr.upload.addEventListener('progress',progressHandling, false);
            }
            return myXhr;
        },
        success: completeHandler,
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
});

var progressHandling = function(e){
    if(e.lengthComputable){
        var percent = Math.round((e.loaded / e.total) * 100);
        $('#uploadprogress').css('width', percent+'%');
    }
}

var completeHandler = function(data){
    $('#message').text(data);
    $('#uploadprogress').css('width', '0%');
    $('#file').val('');
};
});     

PHP

<?php
if ($_FILES["file"]["error"] > 0) {

} else {
  move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
  echo true;
}
?>

2 Answers2

3

Sample Example of Sending form data in ajax call with .serialize()

var formData = $('#myform').serialize;
    $.ajax({
        url: 'uploadFile.php',  
        type: 'POST',
        xhr: function() {  
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ 
                myXhr.upload.addEventListener('progress',progressHandling, false);
            }
            return myXhr;
        },
        success: completeHandler,
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });

If you want to add a string simply use like following:

var value = 'test';
var formData = $('#myform').serialize+"&newstring="+value;

Update

File upload is not possible through ajax. You can upload file, without refreshing page by using IFrame or AjaxFileUpload Plugin.

Further Details here is Answer.

Also file some detail explanation here also:

Community
  • 1
  • 1
Manwal
  • 22,117
  • 10
  • 57
  • 89
0

You could use the HTML5 Upload element.

$("#FileUpload").change(function (e) {
 var uploadFile = e.target.files;
 if (uploadFile.length > 0) {
      if (window.FormData !== undefined) {
           var data = new FormData();
           for (var x = 0; x < uploadFile.length; x++) {
                data.append("file" + x, uploadFile[x]);
           }
           data.append("ELEMENTCLASSNAME", $("#ELEMENTID").val());
           $.ajax({
                type: "POST",
                url: 'URL',
                contentType: false,
                processData: false,
                data: data,
                success: function (result) {
                     alert(result);
                },
                failure: function (result) {
                     alert(result);
                },
                error: function (xhr, status, p3, p4) {
                     var err = "Error " + " " + status + " " + p3 + " " + p4;
                     if (xhr.responseText && xhr.responseText[0] == "{")
                          err = JSON.parse(xhr.responseText).Message;
                     console.log(err);
                }
           });
      } else {
           alert("This browser doesn't support HTML5 file uploads!");
      }
 }});

On the server side use the Request Object get the value:

              var versionName = Request["ELEMENTCLASSNAME"];
ashveli
  • 182
  • 5
  • 20