Text Content and FileUpload with AJAX

I am writing a client database system for my company. Not very fancy stuff, but it does what it should. Now that all the basic β€œtext” things are done, I want to add some file management to it.

I have several forms that submit to the server with ajax and then write to db in the model.

Some of these forms plan to upload a document file.

Is there a way to handle normal values ​​and send the file using AJAX?

Let me give an example of FORM:

<form action="SOMEPATH/LOGIC_FILE.php" action="POST" enctype= multipart/form-data>
  <label for="name">
   <input type="text" id="name" name="name" />
  </label>
  <label for="somethingElse">
   <input type="text" id="somethingElse" name="somethingElse" />
  </label>
  <label for="fileUpload">
    <input type="file" />
  </label>
</form>

AJAX Example:

var name = $('#name').val();
var somethingElse = $('#somethingElse').val();

var dataArr = { 'name':name, 'somethingElse':somethingElse};
MYELEMENT.click(function(e){
e.preventEventDefault();
$.ajax({
            url: "PATH/logic/logic_update_client_allg.php",
            type: "POST",
            data: allgArray,
            success: function(dataArr){
                // works
            },
            error: function(){
                // doesnt work
            }
        });
}

The way I process the input value is INPUT VALUE

How can I continue to upload a file using this form

thank

+4
source share
2 answers

ajax xmlHttpRequest, jQuery.ajax(), FormData.

IE, 7,8, FormData. , contentType, processData false.

. :

var name = $('#name').val();
var somethingElse = $('#somethingElse').val();
var fd = new FormData();
var dataArr = {
  name: name,
  somethingElse: somethingElse,
  file : fd.append('file', $('#fileUpload').get(0).files[0]) // put the file here
};

MYELEMENT.click(function(e) {
  e.preventDefault();
  $.ajax({
    url: "PATH/logic/logic_update_client_allg.php",
    type: "POST",
    data: dataArr, //<----post here the files and other values
    processData: false,  // tell jQuery not to process the data
    contentType: false   // tell jQuery not to set contentType
    success: function(dataArr) {
      // works
    },
    error: function() {
      // doesnt work
    }
  });
});
+5
0

All Articles