简体   繁体   中英

Sending input[type=file] through ajax to CodeIgniter using jQuery.form

Here is the basic html form:

<?php echo form_open( 'controller' ); ?>  
  <fieldset>
    <input type="text" name="field_name_1" value="<?php echo set_value('field_name_1'); ?>"/>
    <input type="file" name="field_name_2" value="<?php echo set_value('field_name_2'); ?>"/>
    // more dynamically added form fields
    <input type="submit" />
  </fieldset>
<?php echo form_close(); ?>

I want my input[type=file] to be sent to its controller (together with the other input types as one) via ajax and the jQuery Form Plugin .

I have the code below that works on all the other input types except for input[type=file] .

<script src="http://malsup.github.com/jquery.form.js"></script> 

var options = {
    url: "<?php echo site_url('new_account/validate_new_account'); ?>",
    type: 'POST',
    dataType: 'json',
    success: function(data) {

      if (data.length === 0) {
        alert('Form successfully submitted!');
      } else {
        alert("Some fields weren't answered successfully. Please answer them.");
        // attach server-side form validations to respective fields
        $.each(data, function(key, value){
          var container = '<div class="error">'+value+'</div>';
          $('.form-element input[name="'+key+'"]').after(container);
        });
      }

    }
};

$('#main-submit').click(function(e) {
  $('#professional-form').valid(); // jQuery validate
  $('#professional-form').ajaxSubmit(options);  
  e.preventDefault(); // redirect to other place only if successful form 
});

The other input fields are sent successfully but CodeIgniter still does not receive the file . Do you guys know how to fix this?

File upload is not generally possible via standard ajax posting. However there are certain tools out there that allow asynchronous uploading of files:

The reason you can't do this using a standard jquery post is because javascript can't read local files for security reasons. These tools get around the limitation using various solutions such as hidden iframes, Flash, or HTML5 techniques, depending on what is available on the browser.

File upload is possible via ajax with jquery.form.js as mentioned on the following link:

http://malsup.com/jquery/form/#file-upload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM