1

I got some wired problem while posting a form using jquery ajax. i have a multiple image upload field. while i use e.preventDefault() function the images aren't uploading. but while i disable this code. it remains fine. here is my code snippet for markup, js and php

HTML

<form class="shoform" id="contact-entry" name="contact-entry" action="project-up-eng.php" method="post" enctype="multipart/form-data">
<input class="pic" id="img" type="file" multiple="multiple" name="imgfile[]" />
<input class="submitbtn" id="submitbtn" type="submit" value="Add"></input>
</form>

JS

$("#submitbtn").click(function(){


        $("#contact-entry").submit(function() {
        /* Act on the event */

        e.preventDefault();
        $.post('project-up-eng.php',$(this).serialize(), function()
                        {
                        alert("OK");


                    });

    }); 

});

PHP:

mkdir("projects/".$_POST['name']);
$path="projects/".$_POST['name'];
for($i=0;$i<count($_FILES['imgfile']['size']);$i++)
{
$file = $path."/".$_FILES['imgfile']['name'][$i];
move_uploaded_file($_FILES['imgfile']['tmp_name'][$i],$file);   

}

2 Answers2

4

Unfortunately, you can not submit forms with files over AJAX with classic HTML. When you call e.preventDefault(), the regular file upload is not performed, and your $.post you call manually is just unable to do what you want.

You can upload with JavaScript in new browsers with new HTML 5 functionality. See "How can I upload files with AJAX".

Community
  • 1
  • 1
Denis
  • 5,061
  • 1
  • 20
  • 22
0

You do not mention on which element you want to disable default event functionality.

Currently, there is two element #submitbtn and "#contact-entry"

If you want to prevent #submitbtn then

$("#submitbtn").click(function(e){  // just check e in the bracket

        e.preventDefault();
        $("#contact-entry").submit(function() {
        /* Act on the event */

//        e.preventDefault(); this line removed
        $.post('project-up-eng.php',$(this).serialize(), function()
                        {
                        alert("OK");


                    });

    }); 

});

If you want to prevent #contact-entry then

$("#submitbtn").click(function(){

        $("#contact-entry").submit(function(e) { // just check e in the bracket
        /* Act on the event */

       e.preventDefault(); 
        $.post('project-up-eng.php',$(this).serialize(), function()
                        {
                        alert("OK");


                    });

    }); 

});
Parag Kuhikar
  • 485
  • 2
  • 6
  • 17