1

I have a form that has 3 inputs:

[1] text input field for a status update

[2] file upload (for a picture)

[3] text input field for attaching a link

The user toggles between each one depending on what they want to do. For example when choosing [2], inputs [1] and [3] are hidden.

All of these inputs are contained within a single form with id posts_form. Options [1] and [3] post via Ajax to different controllers.

My problem now is with option [2] because it is not possible to upload images using jQuery ajax.

Some solutions I've seen involve using the jQuery Form plugin, but I wonder if it would be possible to do image uploading without the use of a plugin.

For example this would be the code base for uploading which of course doesn't work.

    $.ajax({
        url: 'chat/upload/' + <?php echo $page_id; ?>,
        type: 'POST',
        data: $('#posts_form').serialize(),
        dataType: 'html',
        beforeSend: function(){
              $('#loading').show();
            },          
        success: function(html) {
            $('#attach').replaceWith(html);
            $('#loading').hide();
            $('#posts_form input').val('');
            $('.posts_link').val('');
            $('#chat_input').hide();
            }
        });

Any suggestions on what could be added / changed to permit image upload using jQuery only, without plugins?

Thanks.

2 Answers 2

3

There is no straightforward way to upload a file via AJAX. That is a limitation in HTML4. Workarounds are using an iframe or Flash.

In HTML5, a File API is introduced to solve that problem. Here's a demo of leveraging that API (using a Firefox 3.6+), which allows you to drag and drop an image and load it without sending it back to the server: http://html5demos.com/file-api. It also supports multiple files: http://demos.hacks.mozilla.org/openweb/DnD/.

You can read about that specification on W3.org, if you are keen.

If you cannot depend on clients to have browsers supporting HTML5's File API, you may either roll you own or choose to use a library that implements the iframe workaround:

Sign up to request clarification or add additional context in comments.

1 Comment

thx @william - i am trying jQuery Form but am running into problems in triggering the submit since my button is not rendered by using input type=submit -- see here for the new question I posted -- I will also check your other solutions
1

Your best choice is this plugin. You're wasting your time trying to do it without this.

http://jquery.malsup.com/form/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.