1

I want to submit a multipart/form-data form without leaving my page or reloading using jQuery and AJAX. When I submit it with PHP only it does the job well but leaves the page.

HTML:

<form  action="" id="myform" method="POST" class="myform" enctype="multipart/form-data">
<input type="file" id="image" name="file">
<input  border="4" type="submit" value="submit"  id="sumit" name="submit"  class="button" />

jQuery:

$(function() {
   $('.myform').submit( function() {
        $.ajax({
             url    : 'c_create.php',
            type    : 'POST',
            data    : formdata(),       
            success : function( data ) {
                         alert('ok');       
                      },
            error   : function(){
                         alert('error');
                      } 
        });

        return false;
    });
});

Any help will be greatly appreciated. Thanks in advance. :)

starkshang
  • 8,228
  • 6
  • 41
  • 52
Oskar
  • 2,522
  • 32
  • 37
  • Either submit your form in an iframe, or send the file via ajax. This has been covered many times on SO. Use the search box or google for more info. – Ray Nicholus Jul 03 '13 at 02:39

4 Answers4

1

I would recommend to use a plugin because the uploading process is quite messy. Especially different browsers have slight differences which makes the code update and maintenance hard. I have tested https://github.com/Widen/fine-uploader and it works well.

$(function() {
    var uploader = new qq.FineUploader({

        element : $('#selectImportFile')[0],
        request: {
            // path to server-side upload script
            // url of the server-side upload script, should be on the same 
            endpoint : 'api/docs',
            // additional data to send, name-value pairs
            params : {}
        },
        // validation    
        validation: {
            // ex. ['jpg', 'jpeg', 'png', 'gif'] or []
            allowedExtensions : [ 'xlsx', 'docx' ],
            // each file size limit in bytes
            // this option isn't supported in all browsers
            sizeLimit : 0, // max size   
            minSizeLimit : 0, // min size
        },
        // set to true to output server response to console
        debug : true,

        // events
        callbacks: {
            // you can return false to abort submit
            onSubmit : function(id, fileName) {
                qq.log('submit');
            },
            onProgress : function(id, fileName, loaded, total) {
                qq.log('onprogress');
            },
            onComplete : function(id, fileName, responseJSON) {
                qq.log('completed');
                qq.log('id: ' + id);
                qq.log('fileName: ' + fileName);
                qq.log('responseJSON: ' + responseJSON);
            },
            onCancel : function(id, fileName) {
            },
            onError : function(id, fileName, xhr) {
                qq.log('error');
            }
        },
        showMessage : function(message) {
            qq.log('Server error: ' + message);
        }

    });

});
Ray Nicholus
  • 19,538
  • 14
  • 59
  • 82
Emin
  • 270
  • 1
  • 2
  • 13
0

try to use preventDefault:

$(function(){
   $('.myform').submit( function(event) {
      event.preventDefault();
      ....

or use 'submit button' instead of '.myform':

$('#sumit').click(function(event){
    event.preventDefault();
    ...
mgraph
  • 15,238
  • 4
  • 41
  • 75
0

You have to serialize the data of the form,

and also do a preventDefault(), so the submit button doesn't actually do a reload.

$(function(){

  $('.myform').submit( function(e) {
    e.preventDefault();
    var formData = $(this).serialize(); 
    $.ajax({
         url    : 'c_create.php',
        type    : 'POST',
        cache: false,
        contentType: 'multipart/form-data',
        data    : formData,       
        success : function( data ) {
                     alert('ok');       
                  },
        error   : function(){
                     alert('error');
                  } 
    });

    return false;
});
});

Although multi-part forms can be a bit tricky with ajax.

Heres some further help on the matter...

jQuery AJAX 'multipart/form-data' Not Sending Data?

Community
  • 1
  • 1
Kylie
  • 11,421
  • 11
  • 47
  • 78
-1

In other words, $.ajax(); cannot submit a multipart/form-data it's only going to submit the data but not going to submit the file along, you can try using dojo.form.uploader.

Stanley Amos
  • 222
  • 2
  • 8
  • I am not allowed to use plusgins. I deside and recomend for any one to use jQuery and ajax for string data and serverside script (php,jsp etc ) for file upload. – Oskar Jul 04 '13 at 07:25
  • It'll be more better if you can use a plugin for this issue! – Stanley Amos Jul 04 '13 at 09:03