Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize file type jQuery

Tags:

jquery

I'm trying to serialize my form data including file image field using jquery.form.js jQuery API. The API is helping me to serailze data fields including image and return image object as [object file]

Here is my code for serialization

    var data = $js("form[name=ajx_imgupload]").formSerialize();
    var img = $js("#upload_image").fieldSerialize();

    $js.ajax({
                 url: "index.php?option=com_obituary&task=upload",
                 type: "POST",
                 dataType:"json",
                 data: data,
                 beforeSend: function(){
                   $js(".loadingblock").show();
                 },
                 complete: function(){
                   $js(".loadingblock").hide();
                 },
                 success: function(res){
                   alert();  
                 },
                 error: function(jqXHR, textStatus, errorThrown){
                   alert(textStatus);                
                 }
           });

Stuck with issue... Help will be much appreciated.

Thanks

like image 353
Maneesh Mehta Avatar asked Sep 04 '12 11:09

Maneesh Mehta


2 Answers

let me help you. I made this just 1 day ago. I have form including image field. when you submit it its uploading image via jquery.form.js

Note: I am uploading file with jqueryimageupload.php, if you want I can paste it. It is a simple php file upload. http://www.w3schools.com/php/php_file_upload.asp

html part:

<form name="imageform" id="imageform" action="jqueryimageupload.php" method="post">
  <input type="file" name="resim" id="img" onchange="ImageUpload()" />
  <input type="hidden" name="action" value="imageup" />
</form>

jquery:

function ImageUpload() {
    $("#return").show();
    $("#return").html('');
    $("#return").html('<img src="images/load2.gif" alt="Uploading...."/> wait, uploading...');
    $("#imageform").ajaxForm({
        target: '#return',
        success: function() {
            $("#return").fadeOut(10000);
        }
   }).submit();     
}

at last form submit:

$('#form').submit(function() {
    var img=$('#image').val();
    var forms=($(this).serialize());
    $.ajax({
        type:"POST",            
        url: "do.php?do=upload",
        data:forms+'&r='+encodeURIComponent(img),
        success: function(result){ //your code }     
    });
 });
like image 151
guybennet Avatar answered Nov 14 '22 00:11

guybennet


You can use this way (from http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/)

$( '#my-form' )
  .submit( function( e ) {
    $.ajax( {
      url: 'http://host.com/action/',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
  } );

it's more flexible and easy way

like image 9
Trofimov Igor Avatar answered Nov 14 '22 00:11

Trofimov Igor