2

For some reason I can not get the following script to work correctly, when submitting the form without using the script all works as it should, but when using the script to submit the form I only get the category and description in the post variables but no file. So my question is how do I get the script to post the file variable also.

Ajax

$("#img-post").click(function()
{
    $("#imgupload").submit(function(e)
    {
        var postData = $(this).serializeArray();
        var formURL = $(this).attr("action");
        $.ajax(
        {
            url : formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus, jqXHR) 
            {
                $("#img").html('<pre><code class="prettyprint">'+data+'</code></pre>');

            },
            error: function(jqXHR, textStatus, errorThrown) 
            {
                alert('Error');
                document.getElementById('enquiry').style.visibility = 'hidden';
            }
        });
        e.preventDefault(); //STOP default action
    });

    $("#imgupload").submit(); //SUBMIT FORM
});

HTML

<div class="img" id="img"></div>

<form name="imgupload" id="imgupload" action="upload.php" method="post" enctype="multipart/form-data">
<input name="category" id="category" type="text" />
<input name="file" id="file" type="file" />
<textarea name="discription" id="discription" cols="68%" rows="8"></textarea><br>
<input type="button"  id="img-post" name="img-post" value="Add" />
</form>
3

1 Answer 1

3

Data from file select elements is not serialized

Taken from the docs page at:

https://api.jquery.com/serializeArray/



However, you can achieve this with the jquery ajax form plugin found here:

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

This plugin is nice because not only does it capture the form data (including files) you can easily send extra $_POST data in the data attribute of the ajax call along with your form.

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

3 Comments

Thank you, the plugin sounds promising I will look into it.
It may be worth noting that the plugin falls back to using an iframe when xhr2 is not available in older browsers github.com/malsup/form
Thanks andrew, I was hoping to stay clear of iframes, but if it only falls back on older browsers that I can deal with :)

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.