Question

I am submitting a form using ajax jquery. I would like to upload an image along with the other fields.

Is it possible to make changes to my present script to accomplish it or would I need to redo everything :-

My jquery is :-

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript">
    $(function () {
        $(".submit").click(function () {
            var article_title = $("#article_title").val();
            var article_body = $("#article_body").val();

            var dataString = 'article_title=' + article_title + '&article_body=' + article_body;

            if (article_title == '' || article_body == '') {
                $('.success').fadeOut(200).hide();
                $('.error').fadeOut(200).show();
            } else {
                $.ajax({
                    type: "POST",
                    url: "<?php echo site_url().'/main/submit_article'?>",
                    data: dataString,
                    success: function () {
                        //$('.success').fadeIn(200).show();
                        $('#article_form')[0].reset();
                        $('.error').fadeOut(200).hide();
                    }

                });
            }

            return false;
        });
    });
</script>

My HTML form :-

<form name="article_form" id="article_form" class="article_form" method="POST" action="">
    <input type="text" name="article_title" id="article_title" placeholder="Title for your article" /> <!--<input type="file" name="pic" />-->
    <br>
    <textarea rows="12" name="article_body" id="article_body" placeholder="Tell your story"></textarea>
    <br>
    <input type="submit" name="submit" id="submit" value="Post" class="submit"/>
</form>
Était-ce utile?

La solution

Why not to make use of jQuery.form plugin.

This plugin allows to handle file upload efficiently Check here.

For clearing fields

$(':input','#myform').not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');

Autres conseils

Add enctype="multipart/form-data" into your form element.

Let me give you a time saver here, try:

uploadify http://www.uploadify.com/

or you could try:

Jquery Forms malsup.com/jquery/form/

If you need progress bar, multiple uploads, drag and drop https://github.com/valums/file-uploader

Use these tools and plugins and save yourself the stress. Don't reinvent the wheels unless you have a better idea.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top