MacMac
MacMac

Reputation: 35361

Using jQuery Form Plugin not working

I've been trying to figure out how to work this jQuery Form plugin to upload a file, but it doesn't seen to do what I need it to do.

I have the jQuery:

$('.upload-file').click(function()
{   
    $('#htmlForm').ajaxForm({ 
        // target identifies the element(s) to update with the server response 
        target: '#htmlExampleTarget', 

        // success identifies the function to invoke when the server response 
        // has been received; here we apply a fade-in effect to the new content 
        success: function(msg) { 
            $('#htmlExampleTarget').hide().html(msg).fadeIn('slow'); 
        } 
    }); 
});

The HTML:

<div id="container">
    <form action="upload.php" method="post" id="htmlForm" enctype="multipart/form-data">
        <p>E-mail<br />
        <input type="text" name="email" id="email" /></p>
        <p>File<br />
        <input type="file" name="upload" id="upload" /></p>
        <p><input type="button" value="Submit" class="upload-file" /></p>
    </form>
</div>
<div id="htmlExampleTarget"></div>

The jQuery Form plugin is included in the <script> in the <head></head> with the $(document).ready(function() whenever I click on the button to submit the form, it doesn't do anything. Although, if I change it to

<input type="submit" value="Submit" class="upload-file" />

The form submits, but goes to upload.php when I should expect it to output the HTML in the <div id="htmlExampleTarget"></div> and it doesn't do that.

EDIT:

<script type="text/javascript" src="js/jquery.form.min.js"></script>
<script type="text/javascript" src="js/jquery.1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.wmk.min.js"></script>
<script type="text/javascript" src="js/uimg-core.js"></script>

Upvotes: 0

Views: 3793

Answers (1)

Nick Craver
Nick Craver

Reputation: 630627

.ajaxForm() is for setting up a <form>, not submitting it, instead you want to run it on document.ready:

$(function() {
  $('#htmlForm').ajaxForm({ 
    target: '#htmlExampleTarget', 
    success: function(msg) { 
        $('#htmlExampleTarget').hide().html(msg).fadeIn('slow'); 
    } 
  });
});

Then do change your type to be a submit button:

<input type="submit" value="Submit" class="upload-file" />

The alternative (though this doesn't degrade gracefully) is to call .ajaxSubmit() like this:

$('.upload-file').click(function() {   
  $('#htmlForm').ajaxSubmit({ 
    target: '#htmlExampleTarget', 
    success: function(msg) { 
        $('#htmlExampleTarget').hide().html(msg).fadeIn('slow'); 
    }
  });
});

This actually submits the form right now, rather than setting it up to send via AJAX on it's submit handler.

Upvotes: 4

Related Questions